views:

120

answers:

2

Hey guys! I have this little problem:

I have one ViewController which adds 2 subViews in my ViewController so I have something like this:

//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 this is my subclass touchs:

//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
}

Now: How can I do that? The best way is create a linkage in my constructor to save my ViewController? How am I supposed to do that?

Thanks!

+1  A: 

Yes, you should create that link just like you suspected.

Simply add a member variable MyViewController* viewController to your view and set it up when you create the view. If you want to get clever, you can create it as a property.

Beware that you shouldn't retain the viewController from a view though - the view is already retained by the controller and if you have a retain going the other way, you will generate a retain cycle and will cause a leak.

Roger Nolan
A: 

An alternative to creating a linkage is to use notifications.

For example, in IconHolder.h

extern const NSString* kIconHolderTouchedNotification;

In 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];
}

Then in your controller

- (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];
}

Notifications are especially good if you want very weak linkage between objects and do not need two way communication (ie, IconHolder does not need to ask the controller for information), or if you need to notify more than one object of changes.

Peter N Lewis