views:

748

answers:

3

I have the error -[NSCFString stringValue]: unrecognized selector sent to instance 0x1578c when executing this code I don't understand what I'm doing wrong name is a NSString

self.searchValues= [[NSMutableArray alloc] init];
name=@"Bob";
if(self.name!=nil)
   [searchValues addObject: [NSMutableDictionary dictionaryWithObjectsAndKeys:@"Name",@"Label",self.name,@"Value",nil]];
NSLog(@"Array value : %s",[[[searchValues objectAtIndex:0] objectForKey:@"Value"] stringValue]);
+2  A: 

Firstly, you can drop the [... stringValue] message. It isn't necessary, that object is already a string. Secondly, you should use %@ instead of %s for NSString objects.

Note: %@ works for any object at all, for that matter. Try

NSLog(@"Array: %@", searchValues);

Trust me, it's worth trying.

Toon Van Acker
Thank you! I was on it since a couple of hours lol
Mathieu
+2  A: 

There is no "stringValue" method on NSString, thus the error.

If you really want the value as a C-string, the method you want is UTF8String. For your logging case though, you should just change %s to %@, and log the NSString object directly.

smorgan
+1  A: 

There is no need to use stringValue in this case (edit: it is actually an error, as others have posted, because NSString does not have a stringValue method).

The object that comes out of your dictionary is already an NSString. What you should do is allow the NSLog function to handle the object as a proper cocoa object. The code for that is %@, not %s, since %s is for C-style strings.

Here is how it should look:

self.searchValues = [[NSMutableArray alloc] init];
name=@"Bob";
if(self.name!=nil)
{
    [searchValues addObject: [NSMutableDictionary
           dictionaryWithObjectsAndKeys:@"Name", @"Label",
                                        self.name,@"Value",
                                       nil]];

    NSLog(@"Array value: %@", [[searchValues objectAtIndex:0]
                                 objectForKey:@"Value"]);
}
e.James