実践Realm10. テーブル定義
{
"venues": [
{
"id": "4c82f252d92ea09323185072",
"name": "Golden Gate Park",
"contact": {
"phone": "4152522590"
},
"location": {
"lat": 37.773835608329,
"lng": -122.41962432861,
"postalCode": "94103",
"cc": "US",
"state": "California",
"country": "United States"
}
}
]
}
// Venue.h
@interface Venue : RLMObject
@property NSString *id;
@property NSString *name;
@property Contact *contact;
@property Location *location;
@end
// Contact.h
@interface Contact : RLMObject
@property NSString *phone;
@end
// Location.h
@interface Location : RLMObject
@property double lat; // latitude
@property double lng; // longitude
@property NSString *postalCode;
@property NSString *cc;
@property NSString *state;
@property NSString *country;
@end
12. Insert
1 //Extract the array of venues from the response
2 NSArray *venues = json[@"venues"];
3
4 RLMRealm *realm = [RLMRealm defaultRealm];
5 [realm beginWriteTransaction];
6 // Save one Venue object (and dependents)
7 // for each element of the array
8 for (NSDictionary *venue in venues) {
9 [Venue createOrUpdateInDefaultRealmWithObject:venue];
10 }
11 [realm commitWriteTransaction];
13. Insert
1 // Create object
2 Person *author = [[Person alloc] init];
3 author.name = @"David Foster Wallace";
4
5 // Get the default Realm
6 RLMRealm *realm = [RLMRealm defaultRealm];
7 // You only need to do this once (per thread)
8
9 // Add to Realm with transaction
10 [realm beginWriteTransaction];
11 [realm addObject:author];
12 [realm commitWriteTransaction];
contextに依存しない
14. Update
1 // Update an object with a transaction
2 [realm beginWriteTransaction];
3 author.name = @"Thomas Pynchon";
4 [realm commitWriteTransaction];
15. Delete
1 Book *cheeseBook = ... //Book we made previously
2
3 // Update an object with a transaction
4 [realm beginWriteTransaction];
5 [realm deleteObject:cheeseBook];
6 [realm commitWriteTransaction];
16. Fetch
1 // Query using a predicate string
2 RLMResults *tanDogs = [Dog objectsWhere:
@"color = 'tan' AND name BEGINSWITH 'B'"];
3
4 // Query using an NSPredicate object
5 NSPredicate *pred = [NSPredicate predicateWithFormat:
@"color = %@ AND name BEGINSWITH %@“, @"tan", @"B"];
6 tanDogs = [Dog objectsWithPredicate:pred];
17. Fetch
1 RLMResults *tanDogs =
[Dog objectsWhere:@"color = ‘tan'"];
2 RLMResults *tanDogsWithBNames =
[tanDogs objectsWhere:@"name BEGINSWITH 'B'"];
Chaining Queries
18. Fetch
1 // Sort tan dogs with names starting with "B" by name
2 RLMResults *dogs = [Dog objectsWhere:
@"color = 'tan' AND name BEGINSWITH 'B'"];
3 RLMResults *sortedDogs = [dogs sortedResultsUsingProperty:
@"name" ascending:YES];
Sort
20. Async
1 dispatch_async(queue, ^{
2 // Get realm and table instances for this thread
3 RLMRealm *realm = [RLMRealm defaultRealm];
4
5 [realm beginWriteTransaction];
6
7 for (NSInteger idx = 0; idx < 1000; idx++) {
8 [Person createInRealm:realm
9 withObject:@{@"name" : [self randomString],
10 @"birthdate" : [self randomDate]}];
11 }
12
13 // Commit the write transaction
14 // to make this data available to other threads
15 [realm commitWriteTransaction];
16 });
21. Migration
1 [RLMRealm setSchemaVersion:1
2 forRealmAtPath:[RLMRealm defaultRealmPath]
3 withMigrationBlock:^(RLMMigration *migration,
4 NSUInteger oldSchemaVersion) {
5 // We havent migrated anything yet so oldSchemaVersion == 0
6 if (oldSchemaVersion < 1) {
7 // Nothing to do!
8 // Realm will automatically detect new properties and removed
9 properties
10 // And will update the schema on disk automatically
11 }
12 }];
26. テーブル定義 (おさらい)
{
"venues": [
{
"id": "4c82f252d92ea09323185072",
"name": "Golden Gate Park",
"contact": {
"phone": "4152522590"
},
"location": {
"lat": 37.773835608329,
"lng": -122.41962432861,
"postalCode": "94103",
"cc": "US",
"state": "California",
"country": "United States"
}
}
]
}
// Venue.h
@interface Venue : RLMObject
@property NSString *id;
@property NSString *name;
@property Contact *contact;
@property Location *location;
@end
// Contact.h
@interface Contact : RLMObject
@property NSString *phone;
@end
// Location.h
@interface Location : RLMObject
@property double lat; // latitude
@property double lng; // longitude
@property NSString *postalCode;
@property NSString *cc;
@property NSString *state;
@property NSString *country;
@end
27. Init
[[Venue alloc] initWithObject:venue];
• NSString, NSDate, NSDataはnilを許容できない。
• + (NSDictionary *)defaultPropertyValues
• + (NSArray *)ignoredProperties
• NSNullは例外
• JSONオブジェクトからNSNullを削除
• -initWithObject:を自前で実装
• API, DBがコントロール可能か。
28. Notification
1 // Observe Realm Notifications
2 self.token = [realm addNotificationBlock:^(NSString *note,
3 RLMRealm * realm) {
4 [myViewController updateUI];
5 }];
• 強参照必須
(内部はweak to weakのNSMapTable)
30. Multi thread
1 RLMRealm *realm = [RLMRealm realmWithPath:realmPath];
2
3 dispatch_async(queue, ^{
4 RLMRealm *realm = [RLMRealm realmWithPath:realmPath];
5 };
• RLMRealm, RLMObjectなどは異なるスレッド間をまたげ
ない。
• RLMRealmはスレッドID毎にキャッシュされている。
35. Completion
1 dispatch_async(queue, ^{
2 RLMRealm *realm = [self realm];
3 [realm beginWriteTransaction];
4 /* Write process */
5 [realm commitWriteTransaction];
6 dispatch_async(dispatch_get_main_queue(), ^{
7 [[self realm] refresh]; // Ensure update
8 if (completion) completion();
9 });
10 });
36. Async fetch
1 dispatch_async(queue, ^{
2 /* Complex fetch */
3
5 Class resultClass = ...;
6 NSString *primaryKey = ...;
7 NSArray *primaryIDs = ...;
8
9 dispatch_async(dispatch_get_main_queue(), ^{
10 RLMResults *results = [resultClass objectsInRealm:[self realm]
11 where:@"%K IN %@", primaryKey, primaryIDs];
12 });
13 });
• primary keyがある場合限定
• RLMResultsが条件で反映されないのでおすすめはできない
38. Delete ruleがない
1 NSArray *relatedObjects [user oneToOneRelatedObjects];
2 NSArray *objects = [@[user]
arrayByAddingObjectsFromArray:relatedObjects];
3
4 [realm deleteObjects:objects];
• 子オブジェクトが消えない
• Add, Delete時に注意
49. Work In Progress
- Multiprocess
- Fine-grain notifications
- Async queries
- Cascading deletes
- Nullable types
- Sync
- Open source Core