2012-04-19 78 views
2

我有一個很少有UITableView/s和UILabel/s的視圖。我以編程方式創建它們(即不使用NIB)。通過引用(指針)與iOS對象衝突嗎?

我已經鞏固的tableView和標籤製作的方法有簽名:

- (void) CreateTableView:(UITableView*) outTableView andLabel:(UILabel*)OutLabel AtFrame:(CGRect) frame{ 
CGRect labelFrame = frame; 
labelFrame.origin.x = LABEL_LEFT_ALIGNMENT; 
labelFrame.origin.y -= LABEL_TOP_ALIGNMENT; 
labelFrame.size.height = LABEL_HEIGHT; 
outLabel = [[UILabel alloc] initWithFrame:labelFrame]; 
[[self view] addSubview:outLabel]; 

outTableView = [[UITableView alloc] initWithFrame:frame style:UITableViewStyleGrouped]; 
[outTableView setDataSource:self]; 
[outTableView setDelegate:self]; 
[[self view] addSubview:outTableView]; 
} 

這裏,outTableView和outLabel是輸出參數。也就是說,方法完成後,調用者將使用outTableView和outLabel。

我的應用程序有3個tableview實例變量 - tableView1,tableView2,tableView3。和三個標籤實例變量。視圖控制器(調用程序),如:

[self CreateTableView:tableView1 andLabel:label1 AtFrame:frame1]; 
    [self CreateTableView:tableView2 andLabel:label2 AtFrame:frame2]; 
    [self CreateTableView:tableView3 andLabel:label3 AtFrame:frame3]; 

這種方法完成後,*的UILabel呈現在屏幕上,來電者能夠使用的UILabel *對象。奇怪的是,UITableView *對象並非如此。

任何想法,爲什麼會有不同的行爲?

注意:我的應用程序已啓用ARC。

回答

2

錯了。這些參數實際上不包含已分配/初始化的實例,因爲您按值傳遞它們,而不是通過引用傳遞它們。考慮通過一個指向對象,然後分配一個新的實例時提領它:

- (void)createTableView:(UITableView **)tvPtr 
{ 
    *tvPtr = [[UITableView alloc] init...]; 
    // etc. 
} 

調用是這樣的:

UITableView *tv; 
[self createTableView:&tv]; 
+0

感謝響應,H2CO3。其實,我嘗試傳遞指針的地址。我看到的編譯錯誤是「將非本地對象的地址傳遞給__autoreleasing參數進行回寫」 – 2012-04-19 16:15:55

+0

更多的,它與返回指針類似。正如我們所說的,(UITableViewCell *)tableView:(UITableView *)aTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath。在這裏,UITableViewCell *對象創建並返回到框架。它是一樣的概念。不需要指針指向指針。 – 2012-04-19 16:18:42

+0

那麼你爲什麼不只是返回一個指針呢? – 2012-04-19 17:39:43