Storing CGPoint, CGSize and CGRect in Collections with NSValue
March 17, 2010
In an earlier post CGRect, CGSize and CGPoint Functions I demonstrated a number of geometry structures available for representing a point (CGPoint – x and y coordinates), size (CGSize – height and width) and rectangles (CGRect – combination of both).
Unfortunately, you cannot directly store any of the above in a collection, for example an array, as each of these is a C structure, not an object.
No worry, NSValue to the rescue. This object can not only hold the structures mentioned above, it can also hold scalar types such as integers, floating point numbers, characters, etc. And of course, NSValue objects can be stored within collections.
The code that follows will create CGRect, CGPoint and CGRect structures, corresponding NSValue objects for each, and store the later into an NSArray. The code will also reconstitute the original structures from the NSValue objects.
// CGPoint converted to NSValue CGPoint point = CGPointMake(9, 9); NSValue *pointObj = [NSValue valueWithCGPoint:point]; // CGSize converted to NSValue CGSize size = CGSizeMake(100, 100); NSValue *sizeObj = [NSValue valueWithCGSize:size]; // CGRect from CGPoint and CGSize converted to NSValue CGRect rect = CGRectMake(point.x, point.y, size.width, size.height); NSValue *rectObj = [NSValue valueWithCGRect:rect]; // Add the objects to a collection NSArray *array = [NSArray arrayWithObjects:pointObj, sizeObj, rectObj, nil]; // Print to console the objects in the collection NSLog(@"array content: %@", array); // Restore from NSValue to C structures CGPoint pointRestored = [pointObj CGPointValue]; CGSize sizeRestored = [sizeObj CGSizeValue]; CGRect rectRestored = [rectObj CGRectValue]; // Print restored values NSLog(@"point x:%f y:%f", pointRestored.x, pointRestored.y); NSLog(@"size w:%f h:%f", sizeRestored.width, sizeRestored.height); NSLog(@"rect x:%f y:%f w:%f h:%f", rectRestored.origin.x, rectRestored.origin.y, rectRestored.size.width, rectRestored.size.height);
The output from the NSLog statements is below: