2009-06-18 38 views
2

嘿傢伙!我有這個小問題:在子視圖中調用方法

我有一個視圖控制器它增加了2子視圖在我的視圖控制器,所以我有這樣的事情:

//in my viewController.m i have this: 
- (void)startIcons 
{ 
    IconHolder *newIconHolder = [[IconHolder alloc] initWithItem:@"SomeItenName"]; 
    [self.view addSubview:newIconHolder]; 
} 
- (void)onPressIcon targetIcon(IconHolder *)pressedIcon 
{ 
    NSLog(@"IconPressed %@", [pressedIcon getName]); 
} 

這是我的子類沾上:

//And in my IconHolder.m i have this: 
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event 
{ 
    //Here i need to call the method onPressIcon from my ViewController 
} 

現在: 我該怎麼做?最好的方法是在我的構造函數中創建一個鏈接來保存我的ViewController?我該怎麼做?

謝謝!

回答

1

是的,您應該創建該鏈接,就像您懷疑的一樣。

只需將成員變量MyViewController* viewController添加到您的視圖中,並在創建視圖時進行設置。如果你想變得聰明,你可以創建它作爲一個屬性。

請注意,您不應該從視圖中保留viewController,儘管 - 視圖已被控制器保留,並且如果保留以其他方式進行,您將生成一個保留循環並導致泄漏。

0

創建鏈接的替代方法是使用通知。

例如,在IconHolder.h

extern const NSString* kIconHolderTouchedNotification; 

在IconHolder.m

常量的NSString * kIconHolderTouchedNotification = @ 「IconHolderTouchedNotification」;

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event 
{ 
    //Here i need to call the method onPressIcon from my ViewController 
    [[NSNotificationCenter defaultCenter] kIconHolderTouchedNotification object:self]; 
} 
在控制器

然後

- (void) doApplicationRepeatingTimeChanged:(NSNotification *)notification 
{ 
    IconHolder* source = [notification object]; 
} 

- (IBAction) awakeFromNib; 
{ 
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(doIconHolderTouched:) name:kIconHolderTouchedNotification object:pressedIcon]; 
} 

- (void) dealloc 
{ 
    [[NSNotificationCenter defaultCenter] removeObserver:self name: kIconHolderTouchedNotification object:pressedIcon]; 
    [super dealloc]; 
} 

通知,如果你想讓對象之間非常弱聯動,不需要雙向通信(即IconHolder並不需要問的信息,控制器特別好),或者如果您需要通知多個對象的更改。

相關問題