how to handle an data from server without knowing the object type (aka, could be a dictionary or array)
so i make a lot of server calls for my app. what is returned can depend on the result of the server operation.
say i make an api call to "foo" which will return either a hash map/nsdictionary if successful or a bool (or a 0 for false, meaning it did not execute).
with my code, i typecast it to i believe it should be assuming it was a successful operation. i will check to see if i get back something else then i expected, say a BOOL false.
NSString *mapContext = (NSString *) [call xmlrpcCall:@"load_map" withObjects: [NSArray arrayWithObjects:dataCenter.state,nil]];
NSLog(@"mapContext in loadStateMap: %@", mapContext);
if ([mapContext isKindOfClass:[NSDictionary class]])
{
if ([mapContext objectForKey:@"faultCode"])
{
NSLog(@"mapContext: %@", mapContext);
[self defaultAlert:mapContext titleMsg:@"load_map"]开发者_Python百科;
}
}
here i ask the server to load a map. if successfull, it will return a string. if it fails, it will return a dictionary with a fault code and a fault message. since mapContext is instantiated as a string, when i check to see if its a dictionary and check for a key fault code, xcode gives me a warning that mapContext may not respond to "objectForKey". i understand completely why i get the warning, but is there a way i can prevent the warning? it never breaks the app but its annoying to see 30+ warnings about this issue.
Use id
, this is what it is for and that is why so many abstracted foundation classes use them (NSArray anyone).
//problem solved!
id mapContext = [call xmlrpcCall:@"load_map" withObjects: [NSArray arrayWithObjects:dataCenter.state,nil]];
精彩评论