问题
I am trying to set the text of a label from one of the properties of my model object (searchRecipeDetailsVariable
), but I get an error
//Extract number of servings from dictionary and place in model
self.searchedRecipeDetailsVariable.numberOfServings = [self.detailedSearchYummlyRecipeResults objectForKey: @"numberOfServings"];
//log number of servings to check that it works
NSLog(@"Number of Servings, %@",self.searchedRecipeDetailsVariable.numberOfServings);
self.numberOfServingsLabel.text = self.searchedRecipeDetailsVariable.numberOfServings;
When I print the value, I can see the number correctly. However, when I attempt to set numberOfServingsLabel.text
I receive the error:
-[__NSCFNumber isEqualToString:]: unrecognized selector sent to instance 0x9028390
As you can imagine, I am not too sure why. I have tried setting the text directly with a string, like below and this works.
self.numberOfServingsLabel.text = @"500";
Then to test I actually did have a string I tried the below. This works fine.
NSString *test = self.searchedRecipeDetailsVariable.numberOfServings;
NSLog(@"test numberof servings string, %@", test);
When I hover over test
, I printed the description. I don't know if it will be useful but it was:
Printing description of test: 2
When I hover over it, it does say it is an NSString *
and at the end it has (int)2
. Not to sure what that means.
回答1:
-[__NSCFNumber isEqualToString:]: unrecognized selector sent to instance 0x9028390
Just like in any other case, the error message is a meaningful English sentence describing the problem. It tells you that self.searchedRecipeDetailsVariable.numberOfServings
is an NSNumber
. No matter you declared it as an NSString
, since Objective-C is dynamically typed (the compile-time type declaration for an object is just for giving hints to the compiler, it may have nothing to do with reality).
You need to convert it to a string, perhaps using NSNumberFormatter
(the proper way), or getting its description (that's not recommended, the description is never to be relied upon), etc. For example:
NSString *test = [NSString stringWithFormat:@"%d",
self.searchedRecipeDetailsVariable.numberOfServings.intValue];
来源:https://stackoverflow.com/questions/16262668/unrecognized-selector-error-for-isequaltostring-when-setting-text-of-a-label