Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I add CGPoint objects to an NSArray the easy way?

People also ask

Can NSArray contain nil?

arrays can't contain nil.

What is NSArray Objective-C?

The NSArray class contains a number of methods specifically designed to ease the creation and manipulation of arrays within Objective-C programs. Unlike some object oriented programming languages (C# being one example), the objects contained in an array do not all have to be of the same type.

Is NSArray ordered?

An object representing a static ordered collection, for use instead of an Array constant in cases that require reference semantics.


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

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

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

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