我试图从NSDictionary获取一个值并将其放入NSMutableArray中。以下是我的一些代码。
- (IBAction)pressedButton:(id)sender {
NSInteger numberOfResults = 3;
NSString *searchString = @"EMINEM";
NSString *encodedSearchString = [searchString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString *finalSearchString = [NSString stringWithFormat:@"https://itunes.apple.com/search?term=%@&entity=song&limit=%li",encodedSearchString,(long)numberOfResults];
NSURL *searchURL = [NSURL URLWithString:finalSearchString];
dispatch_queue_t iTunesQueryQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(iTunesQueryQueue, ^{
NSError *error = nil;
NSData *data = [[NSData alloc] initWithContentsOfURL:searchURL options:NSDataReadingUncached error:&error];
if (data && !error) {
NSDictionary *JSON = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
NSArray *array = [JSON objectForKey:@"results"];
NSMutableArray *arrayTracks;
for (NSDictionary *bpDictionary in array) {
[arrayTracks addObject:[bpDictionary objectForKey:@"trackName"]];
// _author = [bpDictionary objectForKey:@"trackName"];
dispatch_async(dispatch_get_main_queue(), ^{
self.label.text = [arrayTracks objectAtIndex:0];
// self.label2.text = _author;
// NSLog(@"%@", [array objectAtIndex:0]);
});
}
}
});
}
从上面可以看出,它没有正确地将值放入数组中。如果我将_author
设置为[bpDictionary objectForKey:@"trackName"]
,那么它确实有效,但它会全部通过并将标签设置为数组中的最后一个。上面的代码没有输出任何内容(null)。
答案 0 :(得分:0)
利用基础优势,无需手动迭代阵列。
要获取一系列曲目名称,您只需使用valueForKey:
或valueForKeyPath:
NSArray *trackNames = [JSON valueForKeyPath:@"results.trackName"];
话虽如此,我建议您使用网络API执行网络任务。您永远不应该使用NSData
来检索JSON。坚持NSURLSession,它更干净,专为网络任务而设计。
[[[NSURLSession sharedSession] dataTaskWithURL:itunesSearchURL
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
// now you have a properly downloaded JSON
//and you even have access to the URL response headers and any errors.
}]resume];
顺便说一下,你永远不会初始化trackNames
数组,所以在零值上调用addObject将没有任何效果。