-2

Is that possible to create a CGPoint array in objective-C, I write this code, but it lead to an error!

NSMultableArray *result=[[NSMultableArray alloc]initWithCapacity:10];
CGPoint temp=[Self GetPoint];
result[0]=temp; //Error !!
Hazem Abdullah
  • 1,837
  • 4
  • 23
  • 41

4 Answers4

1

No you can't store CGPoint in array. Array only store pointer types objects. you must wrapped up CGPoint into NSValue then store it in array..

NSMultableArray *result=[[NSMultableArray alloc]initWithCapacity:10];
NSValue *pointvalue = [NSValue valueWithCGPoint:CGPointMake(x, y)];
[result addObject:pointvalue];

On retrieve time

CGPoint *myPoint = [[result objectAtIndex:indexValue] CGPointValue];

Also you can wrap other struct type too https://developer.apple.com/library/ios/documentation/uikit/reference/NSValue_UIKit_Additions/Reference/Reference.html

Tirth
  • 7,801
  • 9
  • 55
  • 88
1

Yes, you need to embed the CGPoints within NSValue objects, something like this:

NSMutableArray *arr = [[NSMutableArray alloc] init];
NSValue *val1 = [NSValue valueWithCGPoint:cgpoint1];
[arr addObject:val1];
// etc.

to extract the CGPoints, use this:

for (NSValue *value in arr) {
    CGPoint cgpoint = value.pointValue;
    // Use point
}

Here's a link to the NSValue UIKit Additions Class Reference.

trojanfoe
  • 120,358
  • 21
  • 212
  • 242
1

You can do this by [result addObject:[NSValue valueWithCGPoint:player.center]];

And decode as below

CGPoint point = [(NSValue *)[result objectAtIndex:0] CGPointValue];
Mani
  • 17,549
  • 13
  • 79
  • 100
1

CGPoint is a struct type, and you can only store objective-c objects into the mutable array. Best way to do it is to wrap it with it NSValue like so [NSValue valueWithCGPoint:temp]

Similar question here: For iPad / iPhone apps, how to have an array of points?

Community
  • 1
  • 1
Infinity
  • 3,695
  • 2
  • 27
  • 35