2011-11-07 22 views
0

我试图从一个功能点基础结构,称为:我不能从一个函数得到的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]  ]; 

但是每次我编译程序都会给我一些错误。

我该如何解决这个问题?

+0

什么编译错误你见过? – 0x8badf00d

+0

2011-11-07 11:25:18.061 myFirstGraphicProgram [40922:40b] 0.174533 2011-11-07 11:25:18.062 myFirstGraphicProgram [40922:40b] - [__ NSPlaceholderArray arrayWithCapacity:]:发送到实例0x4e02a90的无法识别的选择器 2011 -11-07 11:25:18.063 myFirstGraphicProgram [40922:40b] ***因未捕获异常'NSInvalidArgumentException'而终止应用程序,原因:' - [__ NSPlaceholderArray arrayWithCapacity:]:无法识别的选择程序发送到实例0x4e02a90' ***调用第一次扔栈: ( \t。 ) 抛出'NSException'实例后终止 –

+0

你知道你没有使用宽度和高度,是不是?虽然没有解决你的问题。 – dasdom

回答

3

[[NSMutableArray alloc ] arrayWithCapacity:2]肯定是错的。改为尝试[NSMutableArray arrayWithCapacity:2]。此外,只需使用[[self calcRose:3] retain]而不是[[NSArray alloc] initWithArray:[self calcRose:3]],如果您打算保持阵列的时间长于当前的循环遍历,则只需要调用retain

+0

“ - [__ NSPlaceholderArray arrayWithCapacity:]:无法识别的选择器发送到实例0x4e02a90”@austinpowers MrMage说得对。 arrayWithCapacity无法识别的选择器发送给实例,其运行时错误不是编译时间。 – 0x8badf00d

1

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

-(NSArray *) calcRose : (float) theta 
{ 
    int cWidth = 320;  
    int cHeight = 240;  

    return [NSArray arrayWithObjects:[NSNumber numberWithFloat:cWidth],[NSNumber numberWithFloat:cHeight],nil];   
} 

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

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

NSArray *tt = [self calcRose:3]; 
+0

当然,如果你需要一个可变数组,你仍然可以使用'[NSMutableArray arrayWithObjects:...]'。 –

相关问题