2014-05-15 32 views
-2

搭配使用來自API JSON調用的對象填充數組。 嘗試下面的代碼使用來自JSON API的信息填充NSArray呼叫

NSURLRequest *request = [NSURLRequest requestWithURL:url]; 

AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request]; 
operation.responseSerializer = [AFJSONResponseSerializer serializer]; 
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) { 
    self.googlePlacesArrayFromAFNetworking = [responseObjectself.googlePlacesArrayFromAFNetworking = [responseObject objectForKey:@"name"];];  
    NSLog(@"The Array: %@",self.googlePlacesArrayFromAFNetworking);   
    [self.tableView reloadData]; 

} failure:^(AFHTTPRequestOperation *operation, NSError *error) { 

    NSLog(@"Request Failed: %@, %@", error, error.userInfo); 

}]; 

[operation start]; 

的JSON是以下結構

[ 

    { 
    "_id": { 
    "$oid": "53736ca60b9620f12b000000" 
    }, 
    "username": "Admin", 
    "name": "Administrator" 
    } 
] 

系統崩潰的未知時選擇表示。當我指定objectAtIndex:0它會正確填充數組,但然後當我嘗試並填充一個字典,然後填充表視圖它崩潰。任何意見/教程,可以幫助的情況下

編輯

要填充陣列

operation.responseSerializer = [AFJSONResponseSerializer serializer]; 
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) { 
    NSLog(@"%@",[responseObject objectAtIndex:0]); 
    self.googlePlacesArrayFromAFNetworking = [responseObject objectAtIndex:0]; 

要填充字典

static NSString *CellIdentifier = @"Cell"; 
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath]; 

NSDictionary *tempDictionary= [self.googlePlacesArrayFromAFNetworking objectAtIndex:indexPath.row]; 
+0

請澄清你的問題。你的標題讀取了一個'NSarray',但你的問題似乎是在問爲什麼'objectAtIndex:0'在字典上拋出一個錯誤。字典沒有這種方法,這就是爲什麼 –

+0

我在http://nscookbook.com/2013/12/ios-programming-recipe-16-2-populating-a-uitableview-with-data- from-the-web-ios-7-and-afnetworking-2-0 /並且它們填充一個數組,然後NSDictionary * tempDictionary = [self.googlePlacesArrayFromAFNetworking objectAtIndex:indexPath.row]; – user3143907

+0

這不是你發佈的代碼。發佈生成錯誤的代碼併發布錯誤消息。不要將它添加到評論中,編輯你的問題並添加它 –

回答

0

我假設的問題是這樣的:

self.googlePlacesArrayFromAFNetworking = [responseObjectself.googlePlacesArrayFromAFNetworking = [responseObject objectForKey:@"name"];]; 

我不確定這段代碼試圖實現什麼。如果你想拔出name財產,這隻會是一個元素,你可以硬編碼它是這樣的:

self.googlePlacesArrayFromAFNetworking = @[ [responseObject objectForKey:@"name"] ]; 
在這種情況下

@[ ]是創建一個數組,裏面我們把一個元素,它是結果的[responseObject objectForKey:@"name"]

是否會有你需要,你需要再創建一個NSMutableArray,網絡回調重複的進行一個響應的循環中,並使用addObject方法將元素添加到陣列中許多name的。