0

I have a webservice that returns data to my client application in JSON. I am using TouchJson to then deserialize this data into a NSDictionary. Great. The dictionary contains a key, "results" and results contains an NSArray of objects.

These objects look like this when printed to log i.e

NSLog(@"Results Contents: %@",[resultsArray objectAtIndex:0 ]);

Outputs:

Results Contents: {
    creationdate = "2011-06-29 22:03:24";        
    id = 1;
    notes = "This is a test item";
    title = "Test Item";
    "users_id" = 1;
}

I can't determine what type this object is. How do I get the properties and values from this object?

Thanks!

Nick
  • 19,198
  • 51
  • 185
  • 312
  • That's a `NSDictionary` you're seeing there in `Results`. You can tell by seeing the object & key pairs. For example, "users_id" is the key, and `1` is the object. – sudo rm -rf Jun 30 '11 at 23:37
  • It's an NSDictionary. Use `-objectForKey:` to get each one. E.g. `NSString * title = [[resultsArray objectAtIndex:0] objectForKey:@"title"];` – Ben Zotto Jun 30 '11 at 23:38
  • i'm betting they're all NSStrings, but the 1's may be NSNumbers - when printing a dictionary, the quotes are put around a string if there's a space in it, and not if there's not (thus you can't tell that the 1's are/aren't a string – bshirley Jun 30 '11 at 23:40
  • The first is more likely an NSDate. Keep in mind that `%@` calls `-description` on an object, and the description is an `NSString`. – PengOne Jun 30 '11 at 23:41
  • Thanks so much y'all. I didn't realize I was looking at a representation of an nsdictionary – Nick Jul 01 '11 at 00:23

2 Answers2

3

To get the content of a NSDictionary you have to supply the key for the value that you want to retrieve. I.e:

NSString *notes = [[resultsArray objectAtIndex:0] valueForKey:@"notes"];
Peter Warbo
  • 11,136
  • 14
  • 98
  • 193
2

To test if object is an instance of class a, use one of these:

[yourObject isKindOfClass:[a class]]

[yourObject isMemberOfClass:[a class]]

To get object's class name you can use one of these:

const char* className = class_getName([yourObject class]);

NSString *className = NSStringFromClass([yourObject class]); 

For an NSDictionary, you can use -allKeys to return an NSArray of dictionary keys. This will also let you know how many there are (by taking the count of the array). Once you know the type, you can call

[[resultsArray objectAtIndex:0] objectForKey:keyString];

where keyString is one of @"creationdate", @"notes", etc. However, if the class is not a subclass of NSObject, then instead use:

[[resultsArray objectAtIndex:0] valueForKey:keyString];

for example, you probably need to do this for keystring equal to @"id".

PengOne
  • 48,188
  • 17
  • 130
  • 149