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.
我有一个viewController控制器和一个视图A.此外,ViewA包含一个按钮。通常,我们在单击按钮时调用同一类中的函数。但我希望在单击按钮时执行控制器中的方法。
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];
}
1 个解决方案
#1
1
Blocks are the answer to this problem:
块是这个问题的答案:
Class B
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
请注意保留周期
#1
1
Blocks are the answer to this problem:
块是这个问题的答案:
Class B
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
请注意保留周期