从NSMultableArray到CGPoint

时间:2014-01-18 08:16:50

标签: ios objective-c

是否可以在objective-C中创建CGPoint数组,我编写此代码,但它会导致错误!

NSMultableArray *result=[[NSMultableArray alloc]initWithCapacity:10];
CGPoint temp=[Self GetPoint];
result[0]=temp; //Error !!

4 个答案:

答案 0 :(得分:1)

不,你不能将CGPoint存储在数组中。数组仅存储指针类型对象。你必须将CGPoint包裹到NSValue中,然后将其存储在数组中..

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

检索时间

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

您也可以包装其他结构类型https://developer.apple.com/library/ios/documentation/uikit/reference/NSValue_UIKit_Additions/Reference/Reference.html

答案 1 :(得分:1)

是的,您需要将CGPoint嵌入NSValue个对象中,如下所示:

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

提取CGPoint,请使用:

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

这是 NSValue UIKit Additions类参考link

答案 2 :(得分:1)

你可以这样做 [result addObject:[NSValue valueWithCGPoint:player.center]];

解码如下

CGPoint point = [(NSValue *)[result objectAtIndex:0] CGPointValue];

答案 3 :(得分:1)

CGPoint是一种结构类型,您只能将objective-c对象存储到可变数组中。最好的办法是用它来包装NSValue,如[NSValue valueWithCGPoint:temp]

类似的问题:For iPad / iPhone apps, how to have an array of points?