2016-01-13 101 views
7

在我的项目我尝试通过MVVM在VM工作, 所以在.h文件如何绑定Realm对象更改?

@property (nonatomic, strong) NSArray *cities; 

.m文件

- (NSArray *)cities { 
     return [[GPCity allObjects] valueForKey:@"name"]; 
    } 

GPCityRLMObject子 如何通过ReactiveCocoa结合本(我是指查看所有城市的更新/添加/删除)?

喜欢的东西:

RAC(self, cities) = [[GPCity allObjects] map:(GPCity *)city {return city.name;}]; 
+0

你有没有一起来看看在领域文档的ReactiveCocoa例子吗?也许你会在那里找到一些东西:https://github.com/realm/realm-cocoa/tree/master/examples/ios/objc/RACTableView – joern

回答

2

您可以在RAC信号包裹境界变更通知:

@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"]; }]; 

这不幸的是更新后的信号写交易,而不仅仅是那些莫dify城市。一旦境界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 
+0

非常好的例子。正是我在找什么。一个建议。在'addNotificationBlock'行之前,我会建议做一个'[subscriber sendNext:self];'来填充信号中的初始值。 –