2011-11-07 24 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:...]'。 –

相關問題