首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往
21 篇文章
1
iOS开发·第三方数据库处理框架:Realm 基本用法
2
iOS开发·KVC:字典转模型,防止因本地未定义字段(后台的字段与本地字符串名不一致)导致数据转换过程中的奔溃
3
iOS开发·第三方网络下载处理框架:AFNetworking网络下载处理(官方文档翻译篇)
4
iOS开发·NSString字符串的各种基本操作,数值转换及衍生操作
5
iOS开发·NSDate日期基本操作方法
6
iOS开发·必会的算法操作:字符串数组排序+模型对象数组排序
7
iOS开发·UIWindow与视图层级调整技巧(makeKeyWindow,resignKeyWindow,makeKeyAndVisible,keyWindow,windowLevel,UIWind
8
iOS开发·适配iPhone X相关的宏和方法
9
iOS开发·KVO用法,原理与底层实现: runtime模拟实现KVO监听机制(Blcok及Delgate方式)
10
iOS开发·runtime原理与实践: 基本知识篇(类,超类,元类,super_class,isa,对象,方法,SEL,IMP)
11
iOS开发·runtime原理与实践: 关联对象篇(Associated Object)(应用场景:为分类添加“属性”,为UI控件关联事件Block体,为了不重复获得某种数据)
12
iOS开发·runtime+KVC实现多层字典模型转换(多层数据:模型嵌套模型,模型嵌套数组,数组嵌套模型)
13
iOS开发·runtime原理与实践: 方法交换篇(Method Swizzling)(iOS“黑魔法”,埋点统计,禁止UI控件连续点击,防奔溃处理)
14
iOS开发·runtime原理与实践: 消息转发篇(Message Forwarding) (消息机制,方法未实现+API不兼容奔溃,模拟多继承)
15
iOS开发·网络请求方法总结复习(NSURLConnection,NSURLSession,AFNetworking)
16
iOS开发·由SDWebImage引发的知识点聚合与思考(最新呕心沥血之作)
17
iOS开发·RunLoop源码与用法完全解析(输入源,定时源,观察者,线程间通信,端口间通信,NSPort,NSMessagePort,NSMachPort,NSPortMessage)
18
iOS开发·紫色感叹号
19
iOS开发·设置状态栏颜色的小结与误区
20
iOS开发·专职协议声明的头文件
21
iOS开发·状态栏设置技巧2:更新状态栏

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

除了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];
}
下一篇
举报
领券