Domanda

This is the code:

NSString *jsonString = @"[
            {\"sn\": \"E\", \"t\": \"K\", \"d\": \"Tue 3-Mar\"}, 
            {\"sn\": \"F\", \"t\": \"Y 1\", \"d\": \"Tue 3-Mar\"}
         ]";
NSData *data = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSArray *jsArray = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSLog(@"jsArray: %@", jsArray);

for (id job in jsArray) {
    NSLog(@"job: %@", job);
    NSLog(@"%@", [job sn]);
}

In the console, I get this:

2014-04-22 15:40:46.464 test[2442:60b] jsArray: (
        {
        d = "Tue 3-Mar";
        sn = E;
        t = K;
    },
        {
        d = "Tue 3-Mar";
        sn = F;
        t = "Y 1";
    }
)
2014-04-22 15:40:46.466 test[2442:60b] job: {
    d = "Tue 3-Mar";
    sn = E;
    t = K;
}
-[__NSCFDictionary sn]: unrecognized selector sent to instance 0x8fa53b0
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', 
reason: '-[__NSCFDictionary sn]: unrecognized selector sent to instance 0x8fa53b0'

It seems to recognise the array of objects and the individual object. Why does it object to the property sn?

È stato utile?

Soluzione

The jsArray contains dictionaries. So job is an NSDictionary. NSDictionary doesn't have a method named sn. If you want the value for the key @"sn" then you need:

for (NSDictionary *job in jsArray) {
    NSLog(@"job: %@", job);
    NSLog(@"%@", job[@"sn"]);
}

Altri suggerimenti

Your jsArray contains NSDictionaries, So the type of job will be NSDictionary. You can't retrieve value from NSDictionary like that.

Use:

 NSLog(@"%@", [job objectForKey:@"sn"]);
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top