Alex Rivera | Logout

NSDictionary not properly storing CGRect?

Asked 2011-12-29T17:18:24.543
9

I seem to be having problems storing a CGRect into an NSDictionary. The code I'm using:

dictionary = [NSDictionary dictionaryWithObjectsAndKeys:@"Crocodile", [NSValue valueWithCGRect:CGRectMake(100,100,200,200)], nil];

From what I've read, that should wrap my CGRect up into an NSValue and store it into the dictionary.

However, when I tried to NSLog it, the value returns as {{0,0}, {0,0}}

NSLog(@"Crocodile value is: %@", NSStringFromCGRect([[dictionary objectForKey:@"Crocodile"] CGRectValue]));

I have checked my dictionary count and the items seem to be inserted. I'm not sure where this is failing. I've also tried to manually break it down by creating a CGRect var, then an NSValue var, and sticking that into the dictionary with the same results.

Any help appreciated. Thanks

Thank you.

Edit
Report

2 Answers

19

The order of arguments should be (object, key, object, key, …), so in your code the object is @"Crocodile" and the key is the rect.

Swap them and it should work:

dictionary = [NSDictionary dictionaryWithObjectsAndKeys:
    [NSValue valueWithCGRect:CGRectMake(100,100,200,200)], // object first…
    @"Crocodile", // …then key
    nil];

Note that keys aren't required to be instances of NSString, they can be any instance of a class conforming to NSCopying.

answered 2011-12-29T17:23:49.270
10

You can store it as NSString -

        NSStringFromCGRect(<#CGRect rect#>)

And then recover with

         CGRectFromString(<#NSString *string#>)

Good Luck

answered 2011-12-29T17:27:34.710

Your Answer