Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

stringValue of NSDictionary objectForKey runtime error

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?

like image 867
snowbound Avatar asked Dec 03 '22 23:12

snowbound


1 Answers

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.

like image 118
mttrb Avatar answered Mar 05 '23 12:03

mttrb