I have a very bad code written in my program, was just playing around as I am learning Objective C and iOS platform. What I did is,
I have created NSMutableArray like this,
placeInfo = [NSMutableArray array];
and than later in my code I am doing something like this, basically I am manipulating Google places api response(JSON).
NSDictionary *results = [responseString JSONValue];
placeInfo = [results objectForKey:@"result"];
self.phoneNumber = (NSString *)[placeInfo objectForKey:@"formatted_phone_number"]; // In this line compiler warns me that NSMutableArray might not response to this.
I checked documentation but I didn’t find objectForKey in NSMutableArray.
- So what could be the reason? Why my code isn’t crashing? Why it is returning phone number by “formatted_phone_number” key?
EDIT
After first answer I have edited my code and added type casting like this, but it still works.
NSDictionary *results = [responseString JSONValue];
placeInfo = (NSMutableArray *)[results objectForKey:@"result"];
self.phoneNumber = (NSString *)[placeInfo objectForKey:@"formatted_phone_number"];
I’ve never used the Google Places API, but I’d guess
[results objectForKey:@"result"]actually returns another dictionary, so theobjectForKey:works.Because objective-c just uses pointers to refer to objects, it’s never actually being converted to an
NSMutableArray. Also, objective-c doesn’t know at compile time if a method will exist, due to its dynamic nature (you can actually add methods and even whole classes at runtime).Depending on the compiler settings, it may just show a warning that
objectForKey:might not be found at runtime, and let it continue compiling anyway. It ends up working just fine if you actually passed it anNSDictionary.Even when you put the
(NSMutableArray *)cast in front of it, it won’t change anything. That simply casts the pointer type, and doesn’t actually change the object in any way.