Does NSDictionary not store CGRect correctly?

I seem to have problems storing CGRect in an NSDictionary . The code I'm using is:

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

From what I read, this should move my CGRect to NSValue and save it in the dictionary.

However, when I tried to execute the NSLog , the value is returned as {{0,0}, {0,0}}

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

I checked the number of words and the elements seem to be inserted. I am not sure where this is going. I also tried to manually break it up by creating CGRect var, then NSValue var, and sticking to this in a dictionary with the same results.

Any help appreciated. Thanks

Thanks.

+7
source share
2 answers

The order of the arguments must be (object, key, object, key, ...), so in your code the object is @"Crocodile" , and the key is a rectangle.

Change them and it should work:

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

Note that keys are not necessarily instances of NSString; they can be any instance of a class that conforms to NSCopying.

+19
source

You can save it as an NSString -

  NSStringFromCGRect(<#CGRect rect#>) 

And then recover with

  CGRectFromString(<#NSString *string#>) 

Luck

+10
source

All Articles