I have a custom object in which I am trying to write a convenience class method that returns an array of CGPoint structures. The reason for this is there are several methods such as CGPathAddLines which take that as a parameter, and a class method would save me from converting my custom objects to an array of CGPoint structures every time. Unfortunately, I am not sure of the best way to achieve this, especially in regards to memory management.
Here is my implementation thus far:
+ (CGPoint*)CGPointsFromData:(NSArray*)data
{
CGPoint *points = (CGPoint*)malloc(data.count * sizeof(CGPoint));
DataPoint *dataPoint;
int i = 0;
for (id object in data) {
if ([object isKindOfClass:[DataPoint class]]) {
dataPoint = (DataPoint*)object;
points[i] = dataPoint.point;
i++;
}
}
return points;
}
Edit: In case it isn’t clear, the DataPoint class has a property CGPoint point.
If you want this to be a class method, place the word ‘alloc’ or something like it in the method name and place the obligation of free-ing the memory on the caller of your method, then simply return the pointer you allocated (no need to involve variables from any other scope inside this method). Then whomever calls this method can store the pointer in an instance variable and free it whenever appropriate.
and then to consume this (from the same class in this case)