2012-01-15 36 views
0

我有方法之前使用:的UIViewController與指數

self.viewController1 = [[MyViewController alloc] initWithNibName:@"MyViewController" bundle:nil andID:0]; 

但我想再次使用它,它不會自動填充方法與ID,並在包停止。我試圖自己填寫「andID」,它不起作用,就像他們刪除了這個函數或其他東西。

任何想法如何在viewController中實現ID?或者,也許其他想法如何識別相同的類並使用不同的數據加載它們。

謝謝!

+0

你能解釋一下你想要做什麼。你使用這個ID的是什麼? – Hosam 2012-01-15 00:52:03

回答

2

這不是一個標準的UIViewController方法。標準之一是:

- (id)initWithNibName:(NSString *)nibName bundle:(NSBundle *)nibBundle 

...你可能已經使用自定義的方法,這是目前從您的MyViewController實現失蹤。

1

您必須將該方法添加到您的MyViewController類中。

因此,您需要添加一個方法聲明及其相關實現。現在

//MyViewController.h 
@interface MyViewController 
{ 
    int _controllerId; 
} 

@property (nonatomic, assign) int controllerId; 

@end 

//MyViewController.m 
@implementation MyViewController 

@synthesize controllerId = _controllerId; 

- (id)initWithNibName:(NSString *)nibName bundle:(NSBundle *)nibBundle andId:(int)contrId 
{ 
    if(self = [super initWithNibName:nibName bundle:nibBundle]) 
    { 
     self.controllerId = contrId; 
    } 

    return self; 
} 

@end 

您可以創建MyViewController類像下面的實例。

MyViewController myController = [[MyViewController alloc] initWithNibName:@"MyViewController" bundle:nil andID:0]; 
self.viewController1 = myController; 
[myController release]; // if viewController1 has a retain policy 

我建議你不要alloc-init並將新實例分配到同一行中的屬性。事實上,如果你的屬性viewController1有一個保留策略,你會創建一個內存泄漏。在替代:

self.viewController1 = [[[MyViewController alloc] initWithNibName:@"MyViewController" bundle:nil andID:0] autorelease]; // if viewController1 has a retain policy 

的一些注意事項

由於initWithNibName:(NSString *)nibName bundle:(NSBundle *)nibBundle是,你可以把它叫做沒有通過一個id爲您的新方法的公共方法。爲了避免這種情況,您可以將(id)initWithNibName:(NSString *)nibName bundle:(NSBundle *)nibBundle andId:(int)contrId作爲指定的初始值設定項。以這種方式,您不能創建沒有ID的控制器。

+0

@ Paul.s謝謝你,我修好了。 – 2012-01-15 16:22:52

+0

我明白了,謝謝!幫助我 – 2012-01-15 18:31:54