So I have the following code that causes a runtime error in XCode
NSString* temp = [[param objectforkey@"firstParam"] stringValue];
int tempNum = [[param objectforkey@"secondParam"] intValue];
param loads from a plist. firstParam is as string, secondParam is a number
First line crashes the program.
Now what's interesting is it works if I do a hard caste i.e:
NSString* temp = (NSString*)[param objectforkey@"firstParam"];
int tempNum = [[param objectforkey@"secondParam"] intValue];
Just wondering why the id would have inconsistent implementation in that I have to use intValue to cast to int, but have to do hard cast to get NSString? Why not stringValue?
Your first call to objectForKey
returns an object which is an NSString
. NSString
doesn't have a stringValue
method which is why a runtime error is generated. It doesn't make sense to get the stringValue
of something that is already a string.
The second call to objectForKey
returns an NSNumber
. NSNumber
does have an intValue
method so it doesn't cause an error.
In the second case you are changing the type of the returned value from NSNumber
to int
. In the first case the object returned is already an NSString
and there is no point trying to get the stringValue
of a string.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With