前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >iOS开发·第三方数据库处理框架:Realm 基本用法

iOS开发·第三方数据库处理框架:Realm 基本用法

作者头像
陈满iOS
发布2018-09-10 11:16:48
1K0
发布2018-09-10 11:16:48
举报
文章被收录于专栏:陈满iOS陈满iOS

除了FMDB,Realm也是一种很流行的数据库方案。

1. 官方资料

2. 用法示例

2.1 新建数据模型

Student.h

代码语言:javascript
复制
#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 调用前初始化数据库
代码语言:javascript
复制
- (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 增数据
代码语言:javascript
复制
//增
- (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 删数据
代码语言:javascript
复制
//删
- (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 改数据
代码语言:javascript
复制
- (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 查数据
代码语言:javascript
复制
//查
- (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有这样一个需求:第一个账号保存第一个数据库,切换到第二个账号时,再新建第二个数据库,并且无法查看第一个用户的数据,当用户切换回第一个账号时,能继续使用第一个数据库。

代码语言:javascript
复制
- (void)setDefaultRealmForUser:(NSString *)username {
    RLMRealmConfiguration *config = [RLMRealmConfiguration defaultConfiguration];
    
    // 使用默认的目录,但是使用用户名来替换默认的文件名
    config.fileURL = [[[config.fileURL URLByDeletingLastPathComponent]
                       URLByAppendingPathComponent:username]
                      URLByAppendingPathExtension:@"realm"];
    
    // 将这个配置应用到默认的 Realm 数据库当中
    [RLMRealmConfiguration setDefaultConfiguration:config];
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2017.08.16 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 1. 官方资料
  • 2. 用法示例
    • 2.1 新建数据模型
      • 2.2 调用前初始化数据库
        • 2.4 删数据
          • 2.5 改数据
            • 2.6 查数据
              • 2.7 切换用户
              相关产品与服务
              数据库
              云数据库为企业提供了完善的关系型数据库、非关系型数据库、分析型数据库和数据库生态工具。您可以通过产品选择和组合搭建,轻松实现高可靠、高可用性、高性能等数据库需求。云数据库服务也可大幅减少您的运维工作量,更专注于业务发展,让企业一站式享受数据上云及分布式架构的技术红利!
              领券
              问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档