iOS開發·第三方數據庫處理框架:Realm 基本用法

除了FMDB,Realm也是一種很流行的數據庫方案。

1. 官方資料

2. 用法示例

2.1 新建數據模型

Student.h

#import <Realm/Realm.h>
#import <UIKit/UIKit.h>

@interface Student : RLMObject

@property int age;
@property NSString *name;
@property (nonatomic,strong) NSData *showImgData;

@end

// This protocol enables typed collections. i.e.:
// RLMArray<Student>
RLM_ARRAY_TYPE(Student)
2.2 調用前初始化數據庫
- (BOOL)initRealm {
   
   self.isFisrtUser= YES;
   [self setDefaultRealmForUser:[CommonUtils getStrValueInUDWithKey:@"account"]];
   self.userNameLbl.text = @"user1";
   config.fileURL = [[[config.fileURL URLByDeletingLastPathComponent]
   URLByAppendingPathComponent:@"user1"]
   URLByAppendingPathExtension:@"realm"];
   NSLog(@"Realm file path: %@", config.fileURL);
   NSError *error;
   _realm = [RLMRealm realmWithConfiguration:config error:&error];
   if (nil != error) {
     NSLog(@"Create Realm Error");
     return NO;
   }
   NSLog(@"create realm success");
   return YES;
}
2.3 增數據
//增
- (IBAction)onAdd:(id)sender {
   if (_nameTF.text.length ==0 || _ageTF.text.length == 0) {
     UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Empty"
                                                     message:@"Name or Age is empty!"
                                                    delegate:self
                                           cancelButtonTitle:@"Return"
                                           otherButtonTitles:nil];
     [alert show];
     return ;
   }

   Student *s= [Student new];
   s.name = _nameTF.text;
   s.age = [_ageTF.text intValue];
   s.showImgData = UIImagePNGRepresentation(self.showImgeView.image);

   [_realm beginWriteTransaction];
   [_realm addObject:s];
   [_realm commitWriteTransaction];
   UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Sucess"
                                                 message:@"Add Sucess!"
                                                delegate:self
                                       cancelButtonTitle:@"OK"
                                       otherButtonTitles:nil];
   [alert show];
   _allStudents = [Student allObjectsInRealm:_realm];
   [_dataTV reloadData];
}
2.4 刪數據
//刪
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    Student *s = [_allStudents objectAtIndex:indexPath.row];
    if (s == nil) {
        NSLog(@"s is nil");
        return;
    }
    [_realm beginWriteTransaction];
    [_realm deleteObject:s];
    [_realm commitWriteTransaction];
    [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
}
2.5 改數據
- (IBAction)onModify:(id)sender {
    
    if (_nameTF.text.length ==0 || _ageTF.text.length == 0) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Empty"
                                                        message:@"Name or Age is empty!"
                                                       delegate:self
                                              cancelButtonTitle:@"Return"
                                              otherButtonTitles:nil];
        [alert show];
        return ;
    }
    
    
    [_realm beginWriteTransaction];
    _student.name = _nameTF.text;
    _student.age = _ageTF.text.intValue;
    [_realm commitWriteTransaction];
    
    UINavigationController *vc = (UINavigationController *)self.parentViewController;
    [vc popViewControllerAnimated:YES];
}
2.6 查數據
//查
- (IBAction)onQuery:(id)sender {
    if (_filterTF.text.length == 0) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Empty"
                                                        message:@"Filter Age is empty!"
                                                       delegate:self
                                              cancelButtonTitle:@"Return"
                                              otherButtonTitles:nil];
        [alert show];
        return ;
    }

    NSString *filter = [NSString stringWithFormat:@"age > %d", [_filterTF.text intValue ]];
    if (_realm) {
        _allStudents = [Student objectsInRealm:_realm where:filter];
    }
    
    [_dataTV reloadData];
}
2.7 切換用戶

很多App有這樣一個需求:第一個賬號保存第一個數據庫,切換到第二個賬號時,再新建第二個數據庫,并且無法查看第一個用戶的數據,當用戶切換回第一個賬號時,能繼續使用第一個數據庫。

- (void)setDefaultRealmForUser:(NSString *)username {
    RLMRealmConfiguration *config = [RLMRealmConfiguration defaultConfiguration];
    
    // 使用默認的目錄,但是使用用戶名來替換默認的文件名
    config.fileURL = [[[config.fileURL URLByDeletingLastPathComponent]
                       URLByAppendingPathComponent:username]
                      URLByAppendingPathExtension:@"realm"];
    
    // 將這個配置應用到默認的 Realm 數據庫當中
    [RLMRealmConfiguration setDefaultConfiguration:config];
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容