Skip to content

Instantly share code, notes, and snippets.

@rbaulin
Last active August 29, 2015 14:21
Show Gist options
  • Save rbaulin/29eb1da6eeb52233ecd1 to your computer and use it in GitHub Desktop.
Save rbaulin/29eb1da6eeb52233ecd1 to your computer and use it in GitHub Desktop.
Realm dynamic API usage example
#import <Realm.h>
// extracted from RLMRealm_Dynamic.h
@interface RLMProperty (AGDynamic)
- (instancetype)initWithName:(NSString *)name
type:(RLMPropertyType)type
objectClassName:(NSString *)objectClassName
indexed:(BOOL)indexed;
@end
@interface RLMObjectSchema (AGDynamic)
- (instancetype)initWithClassName:(NSString *)objectClassName objectClass:(Class)objectClass properties:(NSArray *)properties;
@end
@interface RLMRealm (AGDynamic)
+ (instancetype)realmWithPath:(NSString *)path
key:(NSData *)key
readOnly:(BOOL)readonly
inMemory:(BOOL)inMemory
dynamic:(BOOL)dynamic
schema:(RLMSchema *)customSchema
error:(NSError **)outError;
- (RLMResults *)allObjects:(NSString *)className;
- (RLMObject *)createObject:(NSString *)className withValue:(id)value;
@end
// extracted from RLMSchema_Private.h
@interface RLMSchema (AGDynamic)
@property (nonatomic, readwrite, copy) NSArray *objectSchema;
@end
// also see realm dynamic tests
// https://github.com/realm/realm-cocoa/blob/123f97cdb2819397e289e088558f36e365e712a7/Realm/Tests/DynamicTests.m
- (void)testDynamic {
[RLMRealm setSchemaVersion:1 forRealmAtPath:RLMTestRealmPath() withMigrationBlock:^(RLMMigration *migration, NSUInteger oldSchemaVersion) {
}];
RLMProperty *propA = [[RLMProperty alloc] initWithName:@"uuid" type:RLMPropertyTypeString objectClassName:nil indexed:YES];
RLMProperty *propB = [[RLMProperty alloc] initWithName:@"title" type:RLMPropertyTypeString objectClassName:nil indexed:NO];
RLMObjectSchema *objectSchema = [[RLMObjectSchema alloc] initWithClassName:@"TrulyDynamicObject" objectClass:RLMObject.class properties:@[propA, propB]];
RLMSchema *schema = [[RLMSchema alloc] init]; // it would be great to have RLMSchema method like +schemaWithClassName:objectClass:properties
schema.objectSchema = @[objectSchema];
RLMRealm *dyrealm = [RLMRealm realmWithPath:RLMTestRealmPath() key:nil readOnly:NO inMemory:NO dynamic:YES schema:schema error:nil];
[dyrealm beginWriteTransaction];
[dyrealm createObject:@"TrulyDynamicObject" withValue:@{@"uuid": [[NSUUID UUID] UUIDString], @"title": @"item title"}];
[dyrealm commitWriteTransaction];
RLMResults *results = [dyrealm allObjects:@"TrulyDynamicObject"];
for (id obj in results) {
NSLog(@"%@ %@", obj[@"uuid"], obj[@"title"]);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment