Getting CGRect from array

ajay picture ajay · Mar 25, 2011 · Viewed 11.6k times · Source

For my application I am trying to store CGRect objects into an NSMutableArray. It is loading well and printing in the log statement, but trying to take the CGRects from the array shows an error. Here is a code snippet:

CGRect lineRact = CGRectMake([[attributeDict objectForKey:@"x"] floatValue], 
  [[attributeDict objectForKey:@"y"] floatValue], 
  [[attributeDict objectForKey:@"width"] floatValue], 
  [[attributeDict objectForKey:@"height"] floatValue]);

  [lineRactangle addObject:NSStringFromCGRect(lineRact)];

How can I get the rects back from the array?

Answer

DarkDust picture DarkDust · Mar 25, 2011

A CGRect is a struct, not an object, and thus cannot be stored in NSArrays or NSDictionaries. You can turn it into a string and turn that string back into a CGRect, but the best way is to encapsulate it via an NSValue:

NSValue *myValue = [NSValue valueWithCGRect:myCGRect];

You can then store this NSValue object in arrays and dictionaries. To turn it back into a CGRect, you'd do:

CGRect myOtherCGRect = [myValue CGRectValue];