How to store CGRect values in NSMutableArray?

How would I store CGRect objects in a NSMutableArray, and then later retrieve them?

Upvotes: 114

Views: 26755

Answers (4)

Jane
Jane

Reputation: 145

CGRect rect = CGRectMake( 5, 5, 40, 30 );
NSString* rectAsString = NSStringFromCGRect( rect );
CGRect original = CGRectFromString( rectAsString );

Upvotes: 12

Vaibhav Sharma
Vaibhav Sharma

Reputation: 1123

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]]

Upvotes: 2

Tanvi Jain
Tanvi Jain

Reputation: 937

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);

Upvotes: 1

Jason Coco
Jason Coco

Reputation: 78353

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];

Upvotes: 294

Related Questions