ios - 如何保持对单个持久 Realm 对象的引用
<p><p>我了解如何使用自动更新结果和 Realm 通知来更新我的 UI 的一般概念。对于我的 ViewController 只有每个都有一个 Realm 对象的情况(例如,聊天 Controller 可能具有 RLMResults 或 RLMArray 消息,但只有一个“对话”对象)。 </p>
<p>我已经能够提出以下两种方法,但似乎都不对。实现这一点的正确方法是什么?</p>
<h1>方法 A:</h1>
<pre><code>@interface ViewController ()
@property(nonatomic, assign) NSInteger objectPrimaryKey;
@property(nonatomic, retain) MyRealmObject *realmObject;
@end
@implementation ViewController
- (void)viewDidLoad
{
;
self.objectPrimaryKey = 123;
self.realmObject = [MyDataManager
realmObjectWithID:self.objectPrimaryKey];
// Set realm notification block
__weak typeof(self) weakSelf = self;
self.notification = [
addNotificationBlock:^(NSString *note,
RLMRealm *realm) {
;
}];
;
}
- (void)reloadData {
if(self.realmObject.isInvalidated) {
self.realmObject = [MyDataManager
realmObjectWithID:self.objectPrimaryKey];
}
// Populate the UI with self.realmObject
}
@end
</code></pre>
<h1>方法 B:</h1>
<pre><code>@interface ViewController ()
@property(nonatomic, assign) NSInteger objectPrimaryKey;
@property(nonatomic, retain) RLMResults *realmObjectResults;
@property(nonatomic, readonly) MyRealmObject *realmObject;
@end
@implementation ViewController
- (void)viewDidLoad
{
;
self.objectPrimaryKey = 123;
self.realmObjectResults = [MyDataManager
realmObjectResultsWithID:self.objectPrimaryKey];
// Set realm notification block
__weak typeof(self) weakSelf = self;
self.notification = [
addNotificationBlock:^(NSString *note,
RLMRealm *realm) {
;
}];
;
}
- (void)reloadData {
// Populate the UI with self.realmObject.
// Don't think we need to check isInvalid here?
}
- (MyRealmObject *)realmObject {
return self.realmObjectResults.firstObject;
}
@end
</code></pre></p>
<br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
<p><p>方法“A”是正确的,尽管您的对象唯一会失效的情况是您已将其删除,此时通过 <code>realmObjectWithID:</code> 重新获取它不会有任何影响(假设这是 <a href="https://realm.io/docs/objc/latest/api/Classes/RLMObject.html#/c:objc(cs)RLMObject(cm)objectForPrimaryKey:" rel="noreferrer noopener nofollow"><code>+</code></a> 的一些包装)</p>
<pre><code>@interface ViewController ()
@property(nonatomic, assign) NSInteger objectPrimaryKey;
@property(nonatomic, retain) MyRealmObject *realmObject;
@end
@implementation ViewController
- (void)viewDidLoad
{
;
self.objectPrimaryKey = 123;
self.realmObject = [MyDataManager
realmObjectWithID:self.objectPrimaryKey];
// Set realm notification block
__weak typeof(self) weakSelf = self;
self.notification = [
addNotificationBlock:^(NSString *note,
RLMRealm *realm) {
;
}];
;
}
- (void)updateUI {
// Populate the UI with self.realmObject
}
@end
</code></pre></p>
<p style="font-size: 20px;">关于ios - 如何保持对单个持久 Realm 对象的引用,我们在Stack Overflow上找到一个类似的问题:
<a href="https://stackoverflow.com/questions/34320104/" rel="noreferrer noopener nofollow" style="color: red;">
https://stackoverflow.com/questions/34320104/
</a>
</p>
页:
[1]