How would I store CGRect objects in a NSMutableArray, and then later retrieve them?
Asked
Active
Viewed 2.6k times
114
4 Answers
293
You need to wrap the CG structures in NSValue
classes. So:
NSMutableArray* array = [NSMutableArray mutableArray];
[array addObject:[NSValue valueWithCGRect:CGRectMake(0,0,10,10)]];
CGRect someRect = [[array objectAtIndex:0] CGRectValue];

Jason Coco
- 77,985
- 20
- 184
- 180
-
more examples here: http://iosdevelopertips.com/cocoa/storing-cgpoint-cgsize-and-cgrect-in-collections-using-nsvalue.html – WINSergey Aug 13 '17 at 16:56
-
great answer! would be even more useful if you demonstrated "unboxing" of the stored NSValue back to CGRect. – Motti Shneor Jul 24 '19 at 12:24
-
1Not available on MacOS – Cliff Ribaudo Dec 27 '20 at 13:48
13
CGRect rect = CGRectMake( 5, 5, 40, 30 );
NSString* rectAsString = NSStringFromCGRect( rect );
CGRect original = CGRectFromString( rectAsString );

Jon Schneider
- 25,758
- 23
- 142
- 170

Jane
- 147
- 1
- 2
2
We store the CGRect
,CGPoint
,CMTime
objects in a NSMutableArray
,
[arrayName addObject:[NSValue valueWithCGPoint:MyCGPoint]]
[arrayName addObject:[NSValue valueWithCGRect:MyCGRect]]
[arrayName addObject:[NSValue valueWithCMTime:MyCMTime]]
[arrayName addObject:[NSValue valueWithCMTimeRange:MyCMTimeRange]]

Vaibhav Sharma
- 1,123
- 10
- 22
1
Store string in array.and then get back string and convert that in CGRect back as per the need.
CGRect rect = CGRectMake( 5, 5, 40, 30 );
NSString* rectAsString = NSStringFromCGRect( rect );
NSMutableArray* array = [NSMutableArray mutableArray];
[array addObject:rectAsString];
For converting string in CGRect back use:-
CGRect rect9 = CGRectFromString(rectAsString);

Tanvi Jain
- 917
- 2
- 7
- 19