132

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?

TheNeil
  • 3,321
  • 2
  • 27
  • 52
Thanks
  • 40,109
  • 71
  • 208
  • 322

4 Answers4

330

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
  • 95,172
  • 10
  • 132
  • 126
  • 4
    For scalar types, have a look at NSNumber... you'll see constructors like numberWithBool: numberWithInteger: numberWithFloat:, numberWithUnsignedShort:, etc. – Jarret Hardie May 22 '09 at 20:07
  • 5
    Alternatively you can use NSValue directly: [NSValue valueWithBytes: &someStructSockaddr objCType: @encode(struct sockaddr)] for instance. – Jim Dovey May 23 '09 at 01:42
  • In my case CGPoint p = [val CGPointValue]; did not work. However CGPoint p = [val pointValue]; did work. – Bob Ueland Aug 10 '22 at 10:44
7

I use this:

Create array:

NSArray *myArray = @[[NSValue valueWithCGPoint:CGPointMake(30.0, 150.0)],[NSValue valueWithCGPoint:CGPointMake(41.67, 145.19)]];

Get 1st CGPoint object:

CGPoint myPoint = [myArray[0] CGPointValue];
Tibidabo
  • 21,461
  • 5
  • 90
  • 86
4

You can also write this in a minimal form of:

CGPoint myArray[] = { CGPointMake(5.5, 6.6), CGPointMake(7.7, 8.8) };

CGPoint p2 = myArray[1];
GilesDMiddleton
  • 2,279
  • 22
  • 31
2

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

Ramin
  • 13,343
  • 3
  • 33
  • 35