数据库Realm简单使用

1.CocoaPods

1
pod 'Realm', '~> 1.0.0'

2.建模型

使用Xcode插件能够方便我们创建realm的数据库模型,插件名“RealmPlugin”,在Alcatraz可下。



.h:

1
2
3
4
5
6
7
8
9
10
11
12
13
#import <Realm/Realm.h>
#import "Dog.h"
@interface Person : RLMObject
@property NSString *name;
@property RLMArray<Dog *><Dog> *dogs;
@property NSInteger personId;
@end
// This protocol enables typed collections. i.e.:
// RLMArray<Person>
RLM_ARRAY_TYPE(Person)

.m:

1
2
3
4
5
6
7
8
9
#import "Person.h"
@implementation Person
+ (NSString *)primaryKey{
return @"personId";
}
@end

3.指定默认数据库

实际开发中,可能需要根据不同用户来创建数据库

1
2
3
4
5
6
7
8
9
RLMRealmConfiguration *config = [RLMRealmConfiguration defaultConfiguration];
// Use the default directory, but replace the filename with the username
config.fileURL = [[[config.fileURL URLByDeletingLastPathComponent]
URLByAppendingPathComponent:@"test"]
URLByAppendingPathExtension:@"realm"];
// Set this as the configuration used for the default Realm
[RLMRealmConfiguration setDefaultConfiguration:config];

4.插入数据

1
2
3
4
5
6
7
Person *person = [[Person alloc]init];
person.name = @"大王";
person.personId = 0;
[person.dogs addObjects:dogs];
[realm beginWriteTransaction];
[realm addOrUpdateObject:person];
[realm commitWriteTransaction];

5.查询数据

1
2
3
4
5
RLMResults<Person *> *persons = [Person allObjects];
for (Person *person in persons) {
NSLog(@"%@",person.name);
NSLog(@"%@",person.dogs);
}

6.查看数据库

使用Realm Browser
下载地址:https://itunes.apple.com/app/realm-browser/id1007457278/

Demo地址:https://github.com/m1penny/RealmTest/