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?
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];
[lineRactangle addObject:[NSValue valueWithCGRect:lineRect]];
Use NSValue to wrap CGRect thus store them in NSArrays.
For example:
CGRect r = CGRectMake(1,2,3,4);
NSValue *v = [NSValue valueWithCGRect:rect];
NSArray *a = [NSArray arrayWithObject:v];
CGRect r2 = [[a lastObject] CGRectValue];
See documentation for the other supported structures.
Actually, I don't think any of the answers thus far really address the question ajay asked. The short answer is: You need to supply CGRectMake with the intValue, rather than the floatValue of the dictionary item. If you need to do this for several CGRects, here's a suggested method:
- (CGRect) NSArrayToCGRect: (NSDictionary *) attributeDict
{
int x = [[attributeDict objectForKey:@"x"] intValue];
int y = [[attributeDict objectForKey:@"y"] intValue];
int w = [[attributeDict objectForKey:@"width"] intValue];
int h = [[attributeDict objectForKey:@"height"] intValue];
return CGRectFromString([NSString stringWithFormat: @"{{%d,%d},{%d,%d}}", x, y, w, h]);
}
There may be a more elegant way to accomplish this, but the above code does work.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With