2013-08-23 58 views
-1

我嘗試動態地添加對象到NSArray。 0錯誤出現在XCode中。我不明白這個錯誤與循環和NSMutableArray中的AddObject

但是,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

你能至少發佈錯誤? – WDUK

+1

''nameInsert addObject:[Candy candyOfCategory:@「chocolate」name:item「]];'最後一個報價是做什麼的 - 是直接複製粘貼嗎? – sjwarner

+0

您是否在'NSString'上使用了一個類別?'NSString'沒有任何方法'JSONValue'! – HAS

回答

1

從你的代碼,看來你期望players是字典的數組,因爲你寫

(for NSDictionary *player in players) 

但是,初始化players作爲NSDictionary,而不是一個數組。你會需要它初始化一個數組來代替:

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