是否有可能在Objective-C中創建一個CGPoint數組,但我寫了這段代碼,但它導致了一個錯誤!從NSMultableArray到CGPoint
NSMultableArray *result=[[NSMultableArray alloc]initWithCapacity:10];
CGPoint temp=[Self GetPoint];
result[0]=temp; //Error !!
是否有可能在Objective-C中創建一個CGPoint數組,但我寫了這段代碼,但它導致了一個錯誤!從NSMultableArray到CGPoint
NSMultableArray *result=[[NSMultableArray alloc]initWithCapacity:10];
CGPoint temp=[Self GetPoint];
result[0]=temp; //Error !!
是的,你需要嵌入CGPoint
s在NSValue
對象內,如下所示:
NSMutableArray *arr = [[NSMutableArray alloc] init];
NSValue *val1 = [NSValue valueWithCGPoint:cgpoint1];
[arr addObject:val1];
// etc.
提取CGPoint
S,使用此:
for (NSValue *value in arr) {
CGPoint cgpoint = value.pointValue;
// Use point
}
這裏有一個link到NSValue UIKit的添置類參考。
不,您不能在數組中存儲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
您可以通過 [result addObject:[NSValue valueWithCGPoint:player.center]];
和解碼如下
CGPoint point = [(NSValue *)[result objectAtIndex:0] CGPointValue];
CGPoint是一個結構類型做到這一點,你只能存儲Objective-C對象進入可變數組。做最好的辦法是用它來包裝它NSValue像現在這樣[NSValue valueWithCGPoint:temp]
類似的問題在這裏:For iPad/iPhone apps, how to have an array of points?