如何绑定Realm对象的变化?

Zap*_*ndr 7 mvvm realm ios reactive-cocoa

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

  @property (nonatomic, strong) NSArray    *cities;
Run Code Online (Sandbox Code Playgroud)

.m文件中

  - (NSArray *)cities {
        return [[GPCity allObjects] valueForKey:@"name"];
    }
Run Code Online (Sandbox Code Playgroud)

GPCity是一个RLMObject子类如何通过ReactiveCocoa绑定它(我的意思是看所有城市更新/添加/删除)?

就像是:

RAC(self, cities) = [[GPCity allObjects] map:(GPCity *)city {return city.name;}];
Run Code Online (Sandbox Code Playgroud)

Tho*_*yne 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
Run Code Online (Sandbox Code Playgroud)

然后执行以下操作:

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

不幸的是,这将在每次写入事务后更新信号,而不仅仅是修改城市的信号。一旦 Realm 0.98 发布并支持 per-RLMResults 通知,您将能够执行以下操作,这些操作只会在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
Run Code Online (Sandbox Code Playgroud)