2011-04-29 64 views
0

我想爲按鈕指定一個標記。正常的命令是:從存儲整數的數組中分配按鈕標記

button.tag = 1; 

該標記必須是整數。

我的問題是,我想分配一個整數,我存儲在一個數組(tabReference),它仍然是一個類(currentNoteBook)的一部分。所以,我需要這樣的:

int k = 0;  
button.tag = [currentNoteBook.tabReference objectAtIndex:k]; // This is where I get the warning. 

這似乎並不工作,但由於Xcode中告訴我:傳遞setTag的說法1:將指針整數,未作演員。

我的陣列看起來像這樣(我試圖用整數...):

NSMutableArray *trArray = [[NSMutableArray alloc] init]; 
     NSNumber *anumber = [NSNumber numberWithInteger:1]; 
     [trArray addObject: anumber]; 
     [trArray addObject: anumber]; 
     [trArray addObject: anumber]; 
     [trArray addObject: anumber]; 
currentNoteBook.tabReference = trArray; 

回答

1

NSMutableArray存儲對象的可修改數組。你不能直接在NSMutableArray中存儲一個整數。這就是爲什麼你必須做這樣的事情來存儲一串整數:

NSMutableArray *the_array = [[NSMutableArray alloc] init]; 

int max = 100; 

for (int i = 0; i < max; i++) 
{ 
    NSNumber *temp_number = [NSNumber numberWithInt:arc4random() % max]; 

    [the_array addObject:temp_number]; 
} 

當然,你可以做很多的事情,店裏其他東西一樣在那裏:

NSMutableArray *the_array = [[NSMutableArray alloc] init]; 

int max = 100; 

int max_x = 50; 
int max_y = 25; 
int max_w = 100; 
int max_h = 200; 

for (int i = 0; i < max; i++) 
{ 
    CGFloat temp_x = arc4random() % max_x; 
    CGFloat temp_y = arc4random() % max_y; 
    CGFloat temp_w = arc4random() % max_w; 
    CGFloat temp_h = arc4random() % max_h; 

    CGRect temp_rect = CGRectMake(temp_x, temp_y, temp_w, temp_h); 

    [the_array addObject:[NSValue valueWithCGRect:temp_rect]]; 

} 

當你去檢索這些值,你需要指定你想要的數組,因爲同一個數組可以包含非常不同的對象。

爲了您的整數:

for (int i = 0; i < max; i++) 
{ 
    NSLog(@"%i: %i", i, [[the_array objectAtIndex:i] intValue]); 
} 

對於例如的CGRect:

for (int i = 0; i < max; i++) 
{ 
    CGRect temp_rect = [[the_array objectAtIndex:i] CGRectValue]; 

    NSLog(@"%i: x:%f y:%f w:%f h:%f", i, temp_rect.origin.x, temp_rect.origin.y, temp_rect.size.width, temp_rect.size.height); 

} 

簡而言之,您存儲對象在你的代碼不是整數。你必須把它們作爲對象拉出來,然後提取你的整數來獲取你的數據。

0

就找到了答案在另一個問題,我提出:

它必須是:

btn.tag = [[currentNoteBook.tabReference objectAtIndex:k] intValue]; 
+0

還是,我覺得這很奇怪。我想我把整數放入數組中 - 爲什麼需要intValue ... – 2011-04-29 21:23:06

+0

您在數組中存儲的項目必須是指針類型,所以這就是爲什麼您將它包裝在NSNumber對象中的原因。 – LuckyLuke 2011-04-29 21:25:57

相關問題