ios – 如何绑定Realm对象的更改?

前端之家收集整理的这篇文章主要介绍了ios – 如何绑定Realm对象的更改?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
在我的项目中,我试图通过MVVM工作,
所以在.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
原文链接:https://www.f2er.com/iOS/331437.html

猜你在找的iOS相关文章