有没有办法在不持久化的情况下修改 RLMObject?
Is there a way to modify a RLMObject without persisting it?
我是 Realm 的新手,正在考虑在特定项目中放弃 CoreData 堆栈以支持它,因为我主要只需要本地存储——至少在纸面上,Realm 感觉是完美的搭配。我面临的问题是,如果没有写事务,我找不到修改从 RLMResults 检索的子类 RLMObject 的方法。我知道这是从哪里来的,但在我的具体情况下这是一个问题——用户可以自由修改对象,然后保存或放弃更改。让 Realm 保持最新状态然后在用户取消他的编辑并且所有变通办法对我来说都很脏时回滚是不对的。有没有一种聪明的方法可以自由修改对象,并且只有在用户决定保存他的更改时才点击 createOrUpdate?
您在此处寻找的设计模式可能 "detach" 领域对象,因此您可以在内存中将其修改为 "standalone object"(不绑定到任何领域)。您可以通过从旧对象的值初始化一个新对象来做到这一点:
@interface Dog : RLMObject
@property NSInteger identifier;
@property NSString *name;
@end
@implementation Dog
+ (NSString *)primaryKey {
return @"identifier";
}
@end
// Editing screen...
Dog *standaloneDog = [[Dog alloc] initWithValue:persistedDog];
standaloneDog.name = @"Fido"; // <- no write transaction necessary
// On save:
RLMRealm *realm = [RLMRealm defaultRealm];
[realm transactionWithBlock:^{
// updates the persisted dog with the standalone dog's new values.
[Dog createOrUpdateInRealm:realm withValue:standaloneDog];
}];
// Nothing to do on cancel since the object was standalone.
请参阅 Realm 在 "Updating Objects" 上的 Objective-C 文档以获取更多信息:https://realm.io/docs/objc/latest/#updating-objects
我是 Realm 的新手,正在考虑在特定项目中放弃 CoreData 堆栈以支持它,因为我主要只需要本地存储——至少在纸面上,Realm 感觉是完美的搭配。我面临的问题是,如果没有写事务,我找不到修改从 RLMResults 检索的子类 RLMObject 的方法。我知道这是从哪里来的,但在我的具体情况下这是一个问题——用户可以自由修改对象,然后保存或放弃更改。让 Realm 保持最新状态然后在用户取消他的编辑并且所有变通办法对我来说都很脏时回滚是不对的。有没有一种聪明的方法可以自由修改对象,并且只有在用户决定保存他的更改时才点击 createOrUpdate?
您在此处寻找的设计模式可能 "detach" 领域对象,因此您可以在内存中将其修改为 "standalone object"(不绑定到任何领域)。您可以通过从旧对象的值初始化一个新对象来做到这一点:
@interface Dog : RLMObject
@property NSInteger identifier;
@property NSString *name;
@end
@implementation Dog
+ (NSString *)primaryKey {
return @"identifier";
}
@end
// Editing screen...
Dog *standaloneDog = [[Dog alloc] initWithValue:persistedDog];
standaloneDog.name = @"Fido"; // <- no write transaction necessary
// On save:
RLMRealm *realm = [RLMRealm defaultRealm];
[realm transactionWithBlock:^{
// updates the persisted dog with the standalone dog's new values.
[Dog createOrUpdateInRealm:realm withValue:standaloneDog];
}];
// Nothing to do on cancel since the object was standalone.
请参阅 Realm 在 "Updating Objects" 上的 Objective-C 文档以获取更多信息:https://realm.io/docs/objc/latest/#updating-objects