如何返回数组

时间:2012-09-05 17:42:00

标签: objective-c ios

我需要返回一个数组但不知道如何执行此操作,这是它的外观

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

return position;

但是我收到了不兼容结果的错误。有什么办法绕过这个错误?需要返回多个职位。

3 个答案:

答案 0 :(得分: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);
}

答案 1 :(得分:0)

随着UIKit Apple将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];

答案 2 :(得分: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更方便。