Question

I have a viewController Controller and a view view A. Also ViewA contains a button. Generally, we call a function in the same class to be executed when clicked on button. But I want a method in controller to be executed when clicked on button.

Following are the two methods I have worked out:

//method 1 
//UIView A
-(id)initWithSelector:(SEL)callbackInB withDelegate:(id)delagateB
{
    self = [super init];
    if (self)
    {
         delegate = delegateB;
         myCB = callbackInB;
    }
    return self;
}
//somewhere in UIView A
[btn addTarget:delegate action:myCB forControlEvents:UIControlEventTouchUpInside];

This works fine .But instead of this if I do as second method , it shows "perform selector may leak as the selector function is unknown" .

//method 2
//somewhere in UIView A 
[btn addTarget:self action:@selector(btnPressed:) forControlEvents:UIControlEventTouchUpInside];


-(void)btnPressed:(id)sender
{

    if([delegate respondsToSelector:myCB])
        [delegate performSelector:myCB];

}
Was it helpful?

Solution

Blocks are the answer to this problem:

Class B

@property (copy, nonatomic) void (^myBlock)(void);

 -(id)initWithMyBlock:(void(^)(void))block
 {
    self = [super init];
    if (self)
    {
         self.myBlock = block;
    }
     return self;
 }

[btn addTarget:delegate action:@selector(btnPressed) forControlEvents:UIControlEventTouchUpInside];

- (void)btnPressed {
  if (_myBlock) {
    _myBlock();
  }
}

Just watch out for retain cycles

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top