Question

Tying to populate an array with objects from an API JSON call. Tried the following code

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];

The JSON is of the following structure

 [

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

The system crashes when says unknown selector. When I specify the objectAtIndex:0 it populates the array correctly but then when i try and populate a dictionary which then populates the table view it crashes. Any advice/tutorials that might help the situation

EDIT

To populate the array

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

To populate the dictionary

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

NSDictionary *tempDictionary= [self.googlePlacesArrayFromAFNetworking objectAtIndex:indexPath.row];
Was it helpful?

Solution

I'm assuming the problem is this:

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

I'm not sure what this code is trying to achieve. If you want to pull out the name property and this will only be one element you can hardcode it like this:

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

in this case @[ ] is creating an array, and inside we place one element, which is the result of [responseObject objectForKey:@"name"]

If there will be many name's that you need you need to then create an NSMutableArray, inside the networking callback iterate over the response with a for loop, and use addObject method to add an element to the array.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top