Search code examples
objective-carraysvectorresizable

Create a re-sizable array of CGPoints in objective-c


I am trying to create a re-sizable array of CGPoints in objective-c. I've have looked into using NSMutableArray however it doesnt seem to allow resizing. Is there something else I can use?

thank you


Solution

  • Use an NSMutableArray, but just box your CGPoint structs in NSValue objects. Example:

    CGPoint myPoint = {0,0};
    CGPoint anotherPoint = {42, 69};
    
    NSMutableArray * array = [NSMutableArray array];
    [array addObject:[NSValue valueWithCGPoint:myPoint]];
    [array addObject:[NSValue valueWithCGPoint:anotherPoint]];
    
    CGPoint retrievedPoint = [[array objectAtIndex:0] CGPointValue];
    

    Note that the +valueWithCGPoint: and CGPointValue methods are only available on the iPhone. However if you need this for the Mac, there are similar methods for dealing with NSPoints, and it's trivial to convert a CGPoint to an NSPoint (you can cast or use NSPointFromCGPoint()).