2016-01-13 66 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];'來填充信號中的初始值。 –

相關問題