Storing CGPoint, CGSize and CGRect in Collections using NSValue

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. In this post I will show you how to store CGPoint CGRect CGSize in an Objective-C collection.

NSValue 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:

2013-12-19 13:20:32.808 Sandbox[5324:70b] array content: (
    "NSPoint: {9, 9}",
    "NSSize: {100, 100}",
    "NSRect: {{9, 9}, {100, 100}}"
2013-12-19 13:20:32.808 Sandbox[5324:70b] point x:9.000000 y:9.000000
2013-12-19 13:20:32.809 Sandbox[5324:70b] size  w:100.000000 h:100.000000
2013-12-19 13:20:32.810 Sandbox[5324:70b] rect x:9.000000 y:9.000000 w:100.000000 h:100.000000
  1. Hi thank you, its helpful, i am new in this field

Comments are closed.