我开始了一个项目,练习从Flickr解析JSON并在我的应用程序中显示照片。一切都很完美,除非我尝试多线程练习应用程序的下载部分。我收到错误消息:
*** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayM objectAtIndex:]: index 4294967295 beyond bounds for empty array'
*** First throw call stack:
(0x1c94012 0x10d1e7e 0x1c360b4 0x397f 0xf9103 0xf94df 0xfac4c 0xf97ef 0x2c2c0 0x2c245 0x2c095 0x1c5cafe 0x1c5ca3d 0x1c3a7c2 0x1c39f44 0x1c39e1b 0x1bee7e3 0x1bee668 0x15ffc 0x257d 0x24a5)
libc++abi.dylib: terminate called throwing an exception
这是我尝试编写的代码:
-(void)loadFlickrPhotos {
self.photoURLS = [[NSMutableArray alloc]init];
self.photoTitles = [[NSMutableArray alloc]init];
//Creating second thread here
dispatch_queue_t downloadQ = dispatch_queue_create("Picture Download", NULL);
dispatch_async(downloadQ, ^{
NSString* urlstring = [NSString stringWithFormat:@"http://api.flickr.com/services/rest/?format=json&sort=random&method=flickr.photos.search&tags=rocket&tag_mode=all&api_key=0e2b6aaf8a6901c264acb91f151a3350&nojsoncallback=1"];
NSURL* url = [[NSURL alloc]initWithString:urlstring];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
NSData* data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSDictionary *parsedObject = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSArray* photos = [[parsedObject valueForKey:@"photos"]objectForKey:@"photo"];
for(NSDictionary* photo in photos) {
NSString* photoURLString = [NSString stringWithFormat:@"http://farm%@.static.flickr.com/%@/%@_%@_m.jpg", [photo objectForKey:@"farm"],[photo objectForKey:@"server"],[photo objectForKey:@"id"],[photo objectForKey:@"secret"]];
NSString* photoTitleString = [photo objectForKey:@"title"];
[self.photoURLS addObject:[NSURL URLWithString:photoURLString]];
[self.photoTitles addObject:photoTitleString];
}
NSLog(@"Photo #: %i", self.photoURLS.count);
}); //End of Second Thread
}
答案 0 :(得分:0)
self.photoURLS& self.photoTitles可能不是线程安全属性...
在主线程中执行以下2行
[self.photoURLS addObject:[NSURL URLWithString:photoURLString]];
[self.photoTitles addObject:photoTitleString];