Finger twist
Finger twist

Reputation: 3786

[NSCFString stringValue]: unrecognized selector sent to instance

I'm using this code to query core data and return the value of key, I store the value like this :

 NSString *newName= @"test"; 
 [newShot setValue:newName forKey:@"shotNumber"]; 

and I query like this :

NSManagedObject *mo = [items objectAtIndex:0];  // assuming that array is not empty
  NSString *value = [[mo valueForKey:@"shotNumber"] stringValue];
  NSLog(@"Value : %@",value);

I'm crashing with this message though :

[NSCFString stringValue]: unrecognized selector sent to instance,

does anyone know where that would be coming from ?

Upvotes: 17

Views: 30003

Answers (5)

johnnyb
johnnyb

Reputation: 712

I often times add a category for NSString to handle this:

@interface NSString(JB)
-(NSString *) stringValue;
@end

@implementation NSString(JB)
  -(NSString *) stringValue {
  return self;
}
@end

You can add a similar category to other classes that you want to respond this way.

Upvotes: 5

Kyle Clegg
Kyle Clegg

Reputation: 39480

Note that you could also get this problem if you are trying to access a string property on an object that you think is something else, but is actually a string.

In my case I thought my Hydration object was in fact a hydration, but checking its class via isKindOfClass I found that it was an NSString and realized that I had incorrectly cast it as a Hydration object and that my problem lied further up the chain.

Upvotes: 0

kennytm
kennytm

Reputation: 523674

newName (@"test") is already an NSString. There is no need to call -stringValue to convert it to a string.

NSString *value = [mo valueForKey:@"shotNumber"];

Upvotes: 41

bbum
bbum

Reputation: 162722

[mo valueForKey: @"shotNumber"] is returning a string and NSString (of which NSCFString is an implementation detail) do not implement a stringValue method.

Given that NSNumber does implement stringValue, I'd bet you put an NSString into mo when you thought you were putting in an NSNumber.

Upvotes: 4

Richard J. Ross III
Richard J. Ross III

Reputation: 55583

The value for the key @"shotNumber" is probably of type NSString which is just a wrapper for NSCFString. What you need to do, is, instead of stringValue, use the description method.

Upvotes: 2

Related Questions