Hi 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
Hi 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
NSMutableArray is for objects. For plain old datatypes, use NSMutableData and good old pointer typecasts. It's a resizable unstructured memory buffer, just what you need for a vector of PODs. As for static type safety, Objective C does not give you any of that anyway.
EDIT:
Creating a mutable data object with an initial size n CGPoint structs:
NSMutableData *Data = [NSMutableData dataWithLength: n*sizeof(CGPoint)];
Placing a CGPoint pt into the buffer at the i-th position:
CGPoint pt;
NSRange r = {i*sizeof(CGPoint), sizeof(CGPoint)};
[Data replaceBytesInRange: r withBytes:&pt];
Retrieving a CGPoint from the i-th position into pt:
CGPoint pt;
NSRange r = {i*sizeof(CGPoint), sizeof(CGPoint)};
[Data getBytes: &pt range:r];
Growing the array by n objects:
[Data increaseLengthBy:n*sizeof(CGPoint)];
Hope that covers it. See the NSMutableData reference, and keep in mind that all NSData methods apply to it.
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 NSPoint
s, and it's trivial to convert a CGPoint
to an NSPoint
(you can cast or use NSPointFromCGPoint()
).