我尝试动态地将对象添加到NSArray。 XCode中出现0错误。
但是,IOS模拟器会生成错误并关闭。
我的代码的静态版本可以正常工作。
所以我不明白错误在哪里。
静态版本:
candyArray = [NSArray arrayWithObjects:
[Candy candyOfCategory:@"chocolate" name:@"chocolate bar"],
[Candy candyOfCategory:@"chocolate" name:@"chocolate chip"],
[Candy candyOfCategory:@"chocolate" name:@"dark chocolate"],
[Candy candyOfCategory:@"hard" name:@"lollipop"],
[Candy candyOfCategory:@"hard" name:@"candy cane"],
[Candy candyOfCategory:@"hard" name:@"jaw breaker"],
[Candy candyOfCategory:@"other" name:@"caramel"],
[Candy candyOfCategory:@"other" name:@"sour chew"],
[Candy candyOfCategory:@"other" name:@"peanut butter cup"],
[Candy candyOfCategory:@"other" name:@"gummi bear"], nil];
动态版本:
// get JSON data from URL
NSURLRequest *theRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http:///?view=json"]];
NSURLResponse *resp = nil;
NSError *error = nil;
NSData *response = [NSURLConnection sendSynchronousRequest: theRequest returningResponse: &resp error: &error];
NSString *jsonString = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding]; //your json string from URL request
// PARSINF JSON VALUE
NSDictionary *jsonDictionary = [jsonString JSONValue];
NSDictionary *players = [jsonDictionary objectForKey:@"user"];
// Creating mutablearray who will receive the inputs of json:
NSMutableArray *nameInsert = [[NSMutableArray alloc] init];
for (NSDictionary *player in players)
{
NSString *item = [player objectForKey:@"name"];
[nameInsert addObject: [Candy candyOfCategory:@"chocolate" name:item" ]];
}
candyArray = nameInsert;
如果循环中不包含任何IOS模拟器。
当然,申请表中没有任何内容。
答案 0 :(得分:1)
从你的代码中,你似乎希望players
成为一个字典数组,因为你写了
(for NSDictionary *player in players)
但是,您将players
初始化为NSDictionary
而不是数组。您需要将其初始化为数组:
<击> NSDictionary
击> NSArray *players = [jsonDictionary objectForKey:@"user"];