我的这个解析操作目前运行良好,但我开始注意到它稍微冻结了我的 UI,所以我正在尝试重构并异步完成此操作。但是我遇到了一些问题,希望有人能指出我正确的方向。这是我当前的(同步)代码:
- (NSArray *)eventsFromJSON:(NSString *)objectNotation
{
NSParameterAssert(objectNotation != nil);
NSData *unicodeNotation = [objectNotation dataUsingEncoding:NSUTF8StringEncoding];
NSError *error = nil;
NSDictionary *eventsData = [NSJSONSerialization JSONObjectWithData:unicodeNotation options:0 error:&error];
if (eventsData == nil) {
//invalid JSON
return nil;
}
NSArray *events = [eventsData valueForKeyPath:@"resultsPage.results"];
if (events == nil) {
//parsing error
return nil;
}
NSLog(@"events looks like %@", events);
NSMutableArray *formattedEvents = [NSMutableArray arrayWithCapacity:events.count];
for (id object in [events valueForKeyPath:@"event"]) {
Event *event = [[Event alloc] init];
event.latitude = [object valueForKeyPath:@"location.lat"];
event.longitude = [object valueForKeyPath:@"location.lng"];
event.title = [object valueForKeyPath:@"displayName"];
event.venue = [object valueForKeyPath:@"venue.displayName"];
event.ticketsLink = [NSURL URLWithString:[object valueForKeyPath:@"uri"]];
event.artist = [object valueForKeyPath:@"performance.artist.displayName"];
event.date = [object valueForKeyPath:@"start.datetime"];
[formattedEvents addObject:event];
}
return [NSArray arrayWithArray:formattedEvents];
}
我一直在研究 NSOperationQueue,我正在努力寻找解决方案,因为我想从此方法返回一个数组,而操作队列并不意味着有返回值。我也在看 GCD,我有这样的东西:
- (NSArray *)eventsFromJSON:(NSString *)objectNotation
{
dispatch_queue_t backgroundQueue =
dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
__block NSMutableArray *mutable = [NSMutableArray array];
dispatch_async(backgroundQueue, ^{
NSParameterAssert(objectNotation != nil);
NSData *unicodeNotation = [objectNotation dataUsingEncoding:NSUTF8StringEncoding];
NSError *error = nil;
NSDictionary *eventsData = [NSJSONSerialization JSONObjectWithData:unicodeNotation options:0 error:&error];
if (eventsData == nil) {
//invalid JSON
mutable = nil;
}
NSArray *events = [eventsData valueForKeyPath:@"resultsPage.results"];
if (events == nil) {
//parsing error
mutable = nil;
}
NSLog(@"events looks like %@", events);
NSMutableArray *formattedEvents = [NSMutableArray arrayWithCapacity:events.count];
for (id object in [events valueForKeyPath:@"event"]) {
Event *event = [[Event alloc] init];
event.latitude = [object valueForKeyPath:@"location.lat"];
event.longitude = [object valueForKeyPath:@"location.lng"];
event.title = [object valueForKeyPath:@"displayName"];
event.venue = [object valueForKeyPath:@"venue.displayName"];
event.ticketsLink = [NSURL URLWithString:[object valueForKeyPath:@"uri"]];
event.artist = [object valueForKeyPath:@"performance.artist.displayName"];
event.date = [object valueForKeyPath:@"start.datetime"];
[formattedEvents addObject:event];
}
mutable = [NSMutableArray arrayWithArray:formattedEvents];
});
return [mutable copy];
}
出于某种原因,这似乎在解析完成之前返回了对象,因为我没有从该可变对象中获取任何数据,但我注意到解析确实发生了(我正在注销结果)。谁能给我一个关于如何让这些异步的东西运行的想法?
谢谢!!