在我的项目中,我试图通过MVVM工作,
所以在.h文件中的VM中
所以在.h文件中的VM中
@property (nonatomic,strong) NSArray *cities;
在.m文件中
- (NSArray *)cities { return [[GPCity allObjects] valueForKey:@"name"]; }
GPCity是一个RLMObject子类
如何通过ReactiveCocoa绑定此(我的意思是看所有城市更新/添加/删除)?
就像是:
RAC(self,cities) = [[GPCity allObjects] map:(GPCity *)city {return city.name;}];
解决方法
您可以在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