我无法从函数中获取 NSArray 作为返回值



我试图从一个名为:

的函数中获得一个基于点的结构
-(NSArray *) calcRose : (float) theta
{
    //first calculate x and y 
    //we need to get width and height of uiscreen
    //myPoint[0] = [UIScreen mainScreen].applicationFrame.size.width;
    NSMutableArray *Points = [[NSMutableArray alloc ] arrayWithCapacity:2];
    float angle = [self radians:theta];
    float side = cos(n * angle);
    int cWidth = 320;
    int cHeight = 240;
    float width = cWidth * side * sin(angle) / 2 + cWidth /2;
    float height = cHeight * side * cos(angle) / 2 + cHeight /2;
    [Points addObject:[NSNumber numberWithFloat:cWidth]];
    [Points addObject:[NSNumber numberWithFloat:cHeight]];
    NSArray *myarr = [[[NSArray alloc] initWithArray:Points ]autorelease ];
    return myarr;
}

我使用下面的代码从函数中检索数据:

NSArray *tt = [[ NSArray alloc] initWithArray:[self calcRose:3]     ];

但是每次我编译这个程序时,它都会给我一些错误。

我该如何解决这个问题?

[[NSMutableArray alloc ] arrayWithCapacity:2]肯定是错的。试试[NSMutableArray arrayWithCapacity:2]吧。此外,您可以只使用[[self calcRose:3] retain]而不是[[NSArray alloc] initWithArray:[self calcRose:3]],并且只有在您打算将数组保持在当前运行循环通过的时间更长时才需要调用retain

我想你已经简化了你的问题的目的,但你似乎做了很多不必要的工作。你的问题中的代码可以重写为:

-(NSArray *) calcRose : (float) theta 
{   
    int cWidth = 320;     
    int cHeight = 240;     
    return [NSArray arrayWithObjects:[NSNumber numberWithFloat:cWidth],[NSNumber numberWithFloat:cHeight],nil];        
} 

initWithCapacity和使用可变数组并没有真正给你什么除了头痛。如果你想使用可变数组,只需创建[NSMutableArray array],但它看起来不像你添加那么多对象,所以我建议的方法会更好。

这个方法返回一个自动释放的数组,所以你的调用语句可以只是

NSArray *tt = [self calcRose:3];

最新更新