Reputation: 21
I understand the general concept of how auto-updating results and realm notifications can be used to update my UI. I am trying to wrap my head around the best approach for doing the same for cases where my view controller only every has a single realm object (An example might be a chat controller that has a RLMResults or RLMArray of messages, but only a single "conversation" object).
I have been able to come up with the two approaches below, but neither seems right. What would be the correct way to implement this?
@interface ViewController ()
@property(nonatomic, assign) NSInteger objectPrimaryKey;
@property(nonatomic, retain) MyRealmObject *realmObject;
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
self.objectPrimaryKey = 123;
self.realmObject = [MyDataManager
realmObjectWithID:self.objectPrimaryKey];
// Set realm notification block
__weak typeof(self) weakSelf = self;
self.notification = [[MyDataManager realm]
addNotificationBlock:^(NSString *note,
RLMRealm *realm) {
[weakSelf reloadData];
}];
[self reloadData];
}
- (void)reloadData {
if(self.realmObject.isInvalidated) {
self.realmObject = [MyDataManager
realmObjectWithID:self.objectPrimaryKey];
}
// Populate the UI with self.realmObject
}
@end
@interface ViewController ()
@property(nonatomic, assign) NSInteger objectPrimaryKey;
@property(nonatomic, retain) RLMResults *realmObjectResults;
@property(nonatomic, readonly) MyRealmObject *realmObject;
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
self.objectPrimaryKey = 123;
self.realmObjectResults = [MyDataManager
realmObjectResultsWithID:self.objectPrimaryKey];
// Set realm notification block
__weak typeof(self) weakSelf = self;
self.notification = [[MyDataManager realm]
addNotificationBlock:^(NSString *note,
RLMRealm *realm) {
[weakSelf reloadData];
}];
[self reloadData];
}
- (void)reloadData {
// Populate the UI with self.realmObject.
// Don't think we need to check isInvalid here?
}
- (MyRealmObject *)realmObject {
return self.realmObjectResults.firstObject;
}
@end
Upvotes: 2
Views: 413
Reputation: 14409
Approach "A" is correct, although the only time your object would be invalidated is if you've deleted it, at which point re-obtaining it via realmObjectWithID:
won't make a difference (assuming this is some wrapper around +[RLMObject objectForPrimaryKey:]
)
@interface ViewController ()
@property(nonatomic, assign) NSInteger objectPrimaryKey;
@property(nonatomic, retain) MyRealmObject *realmObject;
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
self.objectPrimaryKey = 123;
self.realmObject = [MyDataManager
realmObjectWithID:self.objectPrimaryKey];
// Set realm notification block
__weak typeof(self) weakSelf = self;
self.notification = [[MyDataManager realm]
addNotificationBlock:^(NSString *note,
RLMRealm *realm) {
[weakSelf updateUI];
}];
[self updateUI];
}
- (void)updateUI {
// Populate the UI with self.realmObject
}
@end
Upvotes: 1