我有一个ViewController在我的ViewController中添加了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?我该怎么做?
谢谢!
答案 0 :(得分:1)
是的,您应该像怀疑的那样创建该链接。
只需在视图中添加成员变量MyViewController* viewController
,然后在创建视图时进行设置。如果你想变得聪明,你可以把它创建为一个属性。
请注意,您不应该从视图中保留viewController - 控制器已经保留了视图,如果您以另一种方式保留,则会生成保留周期并导致泄漏。
答案 1 :(得分:0)
创建链接的另一种方法是使用通知。
例如,在IconHolder.h中
extern const NSString* kIconHolderTouchedNotification;
在IconHolder.m中
const 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不需要向控制器询问信息),或者您需要通知多个更改对象,则通知特别好。