2014-01-18 46 views
-2

是否有可能在Objective-C中創建一個CGPoint數組,但我寫了這段代碼,但它導致了一個錯誤!從NSMultableArray到CGPoint

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

回答

1

是的,你需要嵌入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 
} 

這裏有一個linkNSValue UIKit的添置類參考

1

不,您不能在數組中存儲CGPoint。數組只存儲指針類型對象。你必須包裹起來CGPointNSValue然後將其存儲在陣列..

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

您可以通過 [result addObject:[NSValue valueWithCGPoint:player.center]];

和解碼如下

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