views:

3976

answers:

2

I have about 50 CGPoint objects that describe something like a "path", and I want to add them to an NSArray. It's going to be a method that will just return the corresponding CGPoint for an given index. I don't want to create 50 variables like p1 = ...; p2 = ..., and so on. Is there an easy way that would let me to define those points "instantly" when initializing the NSArray with objects?

+27  A: 

With UIKit Apple added support for CGPoint to NSValue, so you can do:

NSArray *points = [NSArray arrayWithObjects:
                     [NSValue valueWithCGPoint:CGPointMake(5.5, 6.6)],
                     [NSValue valueWithCGPoint:CGPointMake(7.7, 8.8)],
                     nil];

List as many [NSValue] instances as you have CGPoint, and end the list in nil. All objects in this structure are auto-released.

On the flip side, when you're pulling the values out of the array:

NSValue *val = [points objectAtIndex:0];
CGPoint p = [val CGPointValue];
Jarret Hardie
Cool. How would that work for any kind of scalar type?
Thanks
For scalar types, have a look at NSNumber... you'll see constructors like numberWithBool: numberWithInteger: numberWithFloat:, numberWithUnsignedShort:, etc.
Jarret Hardie
Jim Dovey
A: 

Have you taken a look at CFMutableArray? That might work better for you.

Ramin