如何绑定Realm对象的更改?

时间:2016-01-13 14:08:51

标签: ios mvvm realm reactive-cocoa

在我试图通过MVVM工作的项目中, 所以在.h文件中的VM中

  @property (nonatomic, strong) NSArray    *cities;
<{1>}文件中的

.m

- (NSArray *)cities { return [[GPCity allObjects] valueForKey:@"name"]; } GPCity子类 如何通过ReactiveCocoa绑定它(我的意思是看所有城市更新/添加/删除)?

类似的东西:

RLMObject

1 个答案:

答案 0 :(得分:2)

您可以在RAC信号中包装Realm更改通知:

@interface RLMResults (RACSupport)
- (RACSignal *)gp_signal;
@end

@implementation RLMResults (RACSupport)
- (RACSignal *)gp_signal {
    return [RACSignal createSignal:^(id<RACSubscriber> subscriber) {
        id token = [self.realm addNotificationBlock:^(NSString *notification, RLMRealm *realm) {
            if (notification == RLMRealmDidChangeNotification) {
                [subscriber sendNext:self];
            }
        }];

        return [RACDisposable disposableWithBlock:^{
            [self.realm removeNotification:token];
        }];
    }];
}
@end

然后执行:

RAC(self, cities) = [[[RLMObject allObjects] gp_signal]
                     map:^(RLMResults<GPCity *> *cities) { return [cities valueForKey:@"name"]; }];

不幸的是,这会在每次写入事务之后更新信号,而不仅仅是修改城市的信号。一旦Realm 0.98与support for per-RLMResults notifications一起发布,您就可以执行以下操作,只有在GPCity对象更新时才会更新:

@interface RLMResults (RACSupport)
- (RACSignal *)gp_signal;
@end

@implementation RLMResults (RACSupport)
- (RACSignal *)gp_signal {
    return [RACSignal createSignal:^(id<RACSubscriber> subscriber) {
        id token = [self addNotificationBlock:^(RLMResults *results, NSError *error) {
            if (error) {
                [subscriber sendError:error];
            }
            else {
                [subscriber sendNext:results];
            }
        }];

        return [RACDisposable disposableWithBlock:^{
            [token stop];
        }];
    }];
}
@end