newdev1
newdev1

Reputation: 279

NSDictionary valueForKey crash

How can i retrieve the key value from the below NSMutableArray array. The below code crashes on isEqualToString. However i can see the value of nsRet in the variable view window as @\x18\xaa\x01\xc8\a before running that statement.

        NSMutableArray* nsMyList = [[NSMutableArray alloc] init];
        [nsMyList addObject:[NSDictionary dictionaryWithObjectsAndKeys:
                             @"valueOfKey", @"Key",
                             nil]];
        NSString *nsRet = [nsMyList valueForKey:@"Key"];
        if ([nsRet isEqualToString:@"deviceClass"])
        {
            NSLog(@"Key value:%@", nsRet);
        }

Can anyone here please help me get the correct value for the key? Thanks.

Upvotes: 1

Views: 2612

Answers (4)

Julian Osorio
Julian Osorio

Reputation: 1168

I am a bit lost.

In order to access the dictionary you just create you need to obtain the first element in the NSMutableArray and then the dictionary.

It will be something like this:

NSString *nsRet = [nsMyList[0] objectForKey:@"Key"]

I think it can solve it.

Upvotes: 0

Jsdodgers
Jsdodgers

Reputation: 5312

It looks like you are trying to get the valueForKey: on an NSMutableArray rather than on the dictionary.

What you want is:

[[nsMyList objectAtIndex:0] valueForKey:@"Key"];

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727077

This is because you need objectForKey:, not valueForKey:. The valueForKey: method is for key-value programming. Moreover, the call should be on the [nsMyList objectAtIndex:0], like this:

NSString *nsRet = [[nsMyList objectAtIndex:0] objectForKey:@"Key"]

Upvotes: 1

Richard Brown
Richard Brown

Reputation: 11444

You've stored the NSDictionary in an array. The correct access based on your code would be:

NSDictionary *dict = [nsMyList objectAtIndex:0];
nsret = [dict valueForKey:@"Key"];

Upvotes: 1

Related Questions