1

I am a begginer in iOS and i've got a little problem. I don't know how to get a data from JSONObject for the index i, and for the key x.

Just below, there is my code

-(NSMutableArray*)getAll{
    NSMutableArray* liste;

    dispatch_queue_t downloadQueue = dispatch_queue_create("Get All Offers", NULL);

    dispatch_async(downloadQueue, ^{
        NSData *result = [self executePostCall];
        dispatch_async(dispatch_get_main_queue(), ^{

            id strResult=nil;
            NSError* error;
            strResult = [NSJSONSerialization JSONObjectWithData:result options:0 error:&error];
            for(int cpt=0; cpt>[strResult count];cpt++)
            {
                [liste addObject:[NSMutableArray new]];

                // ERREUR ICI !!!!!!!!!

                [[liste objectAtIndex:cpt] addObject:[[NSString alloc] initWithFormat:@"%@",[[strResult  objectAtIndex:cpt] objectForKey:@"titre"]]];
                [[liste objectAtIndex:cpt] addObject:[[NSString alloc] initWithFormat:@"%@",[[strResult objectAtIndex:cpt] objectForKey:@"srcImage"]]];
                [[liste objectAtIndex:cpt] addObject:[[NSString alloc] initWithFormat:@"%@",[[strResult  objectAtIndex:cpt] objectForKey:@"date"]]];
                [[liste objectAtIndex:cpt] addObject:[[NSString alloc] initWithFormat:@"%@",[[strResult  objectAtIndex:cpt] objectForKey:@"prix"]]];
                [[liste objectAtIndex:cpt] addObject:[[NSString alloc] initWithFormat:@"%@",[[strResult  objectAtIndex:cpt] objectForKey:@"ville"]]];
                [[liste objectAtIndex:cpt] addObject:[[NSString alloc] initWithFormat:@"%@",[[strResult objectAtIndex:cpt] objectForKey:@"categorie"]]];
            }


        });
    });
     NSLog(@"liste: %@",liste);
    return liste;
}

I tried to get the object with the key (for example "titre") at the line cpt. Can you help me please ?

I think the problem is when i'm doing [[liste objectAtIndex:cpt] addObject:[[NSString alloc] initWithFormat:@"%@",[[strResult objectAtIndex:cpt] objectForKey:@"titre"]]]; but i don't know how to solve it.

[self executePostCall] is another function which works fine.

Thanks for your help

2
  • Could you show what looks like your JSON response? Commented Apr 16, 2014 at 15:02
  • @Larme the code is just below, thanks for your help Commented Apr 17, 2014 at 7:56

3 Answers 3

2

Depending on the JSON, the object returned from [NSJSONSerialization JSONObjectWithData] is either an NSArray or NSDictionary. If objectAtIndex doesn't work, chances are you are dealing with an NSDictionary.

The safest way to go is to check which one it is in your code:

if([strResult isKindOfClass:NSArray.class]) {
    // Do something that deals with an array

} else if([strResult isKindOfClass:NSDictionary.class]) {
    // Do something that deals with a dictionary

}
Sign up to request clarification or add additional context in comments.

Comments

1

Thanks for the answers @Larme & @Bob Vork.

Just below the executePostCall method:

- (NSData *)executePostCall {
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@", @"http://www.mysite.com/listAllAnn.php"]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

NSString *requestFields = @"";
requestFields = [requestFields stringByAppendingFormat:@"table=%@&", table];
requestFields = [requestFields stringByAppendingFormat:@"limit=%d&", limit];
requestFields = [requestFields stringByAppendingFormat:@"offset=%d", offset];

requestFields = [requestFields stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSData *requestData = [requestFields dataUsingEncoding:NSUTF8StringEncoding];
request.HTTPBody = requestData;
request.HTTPMethod = @"POST";


NSHTTPURLResponse *response = nil;
NSError *error = nil;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
if (error == nil && response.statusCode == 200) {
} else {
    //Error handling
}
return responseData;

}

And this is the webservice "listAllAnn.php" I use to get informations from MySQL database. I am pretty sure that it is ok, because my workmate use it for Android application.

<?php

$response = array();

$db = new DB_CONNECT();

mysql_query('SET CHARACTER SET utf8');


$table=$_POST["table"];
$limit=$_POST["limit"];
$offset=$_POST["offset"];

$result = mysql_query("SELECT * FROM $table WHERE etat = 2 order by date DESC LIMIT $limit OFFSET $offset") or die(mysql_error());

if (mysql_num_rows($result) > 0) {


while ($row = mysql_fetch_array($result)) {
    $ann = array();
    $ann["id"] = $row["id_ann"];
    $ann["cat"] = $row["id_cat"];


    $response[]= $ann;

}

echo json_encode($response);
} else {
$response["success"] = 0;
$response["message"] = "No products found";

echo json_encode($response);
}
?>

the strResult objet sent me that when I make a NSLog

strResult:{
cat = 46;
id = 1496;
}

and When i do

NSLog(@"strResult: %@",[[strResult objectAtIndex:0] objectForKey:@"id"]);

I got:

strResult: 1496

It's look like I have to use the code below to get info, but I don't know which key to use in the first "objectForKey" because i don't have any key in webservice except the ones i'm using to get infos.

[[liste objectAtIndex:cpt] addObject:[[NSString alloc] initWithFormat:@"%@",[[[strResult  objectForKey:@""]objectAtIndex:cpt] objectForKey:@"titre"]]];

1 Comment

Please edit your original question with extra information rather than adding this in the section for answers.
1

try initializaing liste

NSMutableArray* liste=[[NSMutableArray alloc] init]; Also you can directly use [NSString stringWithFormat:@"%@",xyz];

Hope it helps. Let me know the output.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.