Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting CGRect from array

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?

like image 674
ajay Avatar asked Mar 25 '11 11:03

ajay


4 Answers

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];
like image 200
DarkDust Avatar answered Oct 18 '22 02:10

DarkDust


[lineRactangle addObject:[NSValue valueWithCGRect:lineRect]];
like image 40
Kirby Todd Avatar answered Oct 18 '22 00:10

Kirby Todd


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.

like image 7
freespace Avatar answered Oct 18 '22 02:10

freespace


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.

like image 2
mpemburn Avatar answered Oct 18 '22 00:10

mpemburn