我目前正在Reactive Cocoa中迈出第一步,并且我经历了一些陡峭的学习曲线来理解这些原理. 无论如何这里是我已经提出的. 我将NSArray属性绑定到RACSignal,以便能够通过网络对传入的JSON数据做
无论如何这里是我已经提出的.
我将NSArray属性绑定到RACSignal,以便能够通过网络对传入的JSON数据做出反应.
- (void)updateRandomUserData { @weakify(self); RAC(self, users) = [[self fetchRandomUserData] doNext:^(NSDictionary *json){ @strongify(self); NSMutableArray *randomUsers = [NSMutableArray array]; for (NSDictionary *dict in json[@"data"]) { BKRandomUser *randomUser = [MTLJSONAdapter modelOfClass:[BKRandomUser class] fromJSONDictionary:dict error:nil]; [randomUsers addObject:randomUser]; } self.users = randomUsers; }]; }
信号创建如下所示:
- (RACSignal *)fetchRandomUserData { return [[RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) { NSURLRequest *request = [NSURLRequest requestWithURL:url]; AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) { [subscriber sendNext:JSON]; } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON, NSError *error) { [subscriber sendError:error]; }]; [operation start]; return [RACDisposable disposableWithBlock:^{ [operation cancel]; }]; }] doError:^(NSError *error) { NSLog(@"error: %@", [error description]); }];
}
现在,当Web服务不提供任何我希望对此做出反应的数据时.现在应用程序崩溃了以下声明,我真的不明白:
* Terminating app due to uncaught exception ‘NSInternalInconsistencyException’, reason: ‘Received error from name: [[+createSignal:] -doError:] -doNext: in binding for key path “users” on : (null)’
我在这里错过了什么?
谢谢!
接受的答案将解决问题,但有一个更惯用,更优雅的方式来处理这个问题:首先,使用-map:而不是使用-doNext:将JSON转换为用户数组:
RAC(self, users) = [[self fetchRandomUserData] map:^(NSDictionary *json){ NSMutableArray *randomUsers = [NSMutableArray array]; for (NSDictionary *dict in json[@"data"]) { BKRandomUser *randomUser = [MTLJSONAdapter modelOfClass:[BKRandomUser class] fromJSONDictionary:dict error:nil]; [randomUsers addObject:randomUser]; } return randomUsers; }];
然后,要处理错误,您可以使用-catch ::
RAC(self, users) = [[[self fetchRandomUserData] map:^(NSDictionary *json){ NSMutableArray *randomUsers = [NSMutableArray array]; for (NSDictionary *dict in json[@"data"]) { BKRandomUser *randomUser = [MTLJSONAdapter modelOfClass:[BKRandomUser class] fromJSONDictionary:dict error:nil]; [randomUsers addObject:randomUser]; } return randomUsers; }] catch:^(NSError *error) { return [RACSignal return:@[]]; }];
在此示例中,如果发生错误,我们会捕获它并将其替换为空数组.你可以做任何你想做的事.如果您只想忽略整个事情,请将其替换为nil或[RACSignal empty].或者调用另一个返回RACSignal *的方法.