我使用NSMutableArray
来存储来自网络服务的列表表单中的项目。如何从数组中读取数据以显示随机引用。
因为我试图避免两次点击网络服务或者我是否使其复杂化?
NSInteger randomInt = arc4random_uniform(3);
NSString *baseUrl = @"http://movie-quotes.herokuapp.com/api/v1/quotes";
NSString *webServiceUrl= [NSString stringWithFormat:@"%@/%ld", baseUrl,(long)randomInt];
randomQuotes = nil;
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{
// Load the JSON string from our web serivce (in a background thread)
NSDictionary * dictionary = [JSONHelper loadJSONDataFromURL:webServiceUrl];
dispatch_async(dispatch_get_main_queue(), ^{
randomQuotes = [NSMutableArray array];
// Iterate through the array of quotes records in the dictionary
for (NSDictionary * oneQuote in dictionary)
{
Quotes* newQuotes =[[Quotes alloc] init];
// Add our new Customer record to our NSMutableArray
newQuotes.Quote = [oneQuote objectForKey:@"content"];
newQuotes.FilmName = [oneQuote objectForKey:@"film"];
[randomQuotes addObject:newQuotes];
}
});
});
答案 0 :(得分:0)
您可以从这样的数组中获取随机对象。
NSUInteger randomIndex = arc4random_uniform(theArray.count);
[theArray objectAtIndex: randomIndex];
只要保留引号数组,就不需要再次点击Web服务了。