-1

我尝试将对象动态添加到 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 模拟器工作。

当然,应用程序中没有任何内容。

4

1 回答 1

1

从您的代码中,您似乎希望players成为一个字典数组,因为您编写

(for NSDictionary *player in players)

但是,您初始化players为一个NSDictionary而不是一个数组。您需要将其初始化为数组:

NSDictionaryNSArray *players = [jsonDictionary objectForKey:@"user"];

于 2013-08-23T11:09:33.340 回答