2012-09-05 43 views
-1

我需要返回一個數組,但不知道如何做到這一點,這裏是它的外觀如何返回數組

CGPoint position[] = { 
    CGPointMake(500, 200),    
    CGPointMake(500, 200)       
}; 

return position; 

,但我得到不相容結果的誤差。任何繞過這個錯誤的方法?需要返回多個職位。

+0

你真的想要一個這樣的數組嗎?有一個NSMutableArray代替那個通常會更好。 –

回答

1

您可以從陣列獲取的值做這樣的事

NSArray *position = [NSArray arrayWithObjects: 
        [NSValue valueWithCGPoint:CGPointMake(500, 200)], 
        [NSValue valueWithCGPoint:CGPointMake(600, 300)], 
        nil]; 

for(int i=0; i<[position count]; i++) { 
    NSValue *value = [position objectAtIndex:i]; 
    CGPoint point = [value CGPointValue]; 
    NSLog(@"%@",NSStringFromCGPoint(point); 
} 
+0

謝謝,但是索引0處的對象是什麼意思? – user1647261

+0

它將指向數組中的第一個對象。如果你想要第二個對象意味着NSValue * value = [position objectAtIndex:1]; – Aravindhan

+0

好吧,那就是我所想的大聲笑。 – user1647261

0

隨着UIKit的蘋果增加了支持CGPoint至NSValue,所以你可以做:

NSArray *points = [NSArray arrayWithObjects: 
        [NSValue valueWithCGPoint:CGPointMake(5.5, 6.6)], 
        [NSValue valueWithCGPoint:CGPointMake(7.7, 8.8)], 
        nil]; 

列出與CGPoint一樣多的[NSValue]實例,並以nil結尾列表。該結構中的所有對象都是自動釋放的。

在另一面,當你拉動值超出數組:

NSValue *val = [points objectAtIndex:0]; 
CGPoint p = [val CGPointValue]; 
0

如果你不想使用NSArray既然CGPoint是可以返回它的C方式結構

CGPoint *position = malloc(sizeof(CGPoint)*2); 
position[0] = CGPointMake(500,200); 
position[1] = CGPointMake(500,200); 
return position; 

雖然缺點是調用函數不知道數組中元素的數量,但可能需要以其他方式告訴它。

你也需要釋放返回的數組,一旦你完成它使用free();

雖然使用NSArray/NSMutableArray更方便。