在Objective-C中将引用作为实例var进行阻止 [英] Block references as instance vars in Objective-C

查看:77
本文介绍了在Objective-C中将引用作为实例var进行阻止的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有可能将对匿名函数(块)的引用作为实例变量存储在Objective-C中.

I was wondering if it's possible to store a reference to an anonymous function (block) as an instance variable in Objective-C.

我知道如何使用委派,目标动作等.我不是在谈论这个.

I know how to use delegation, target-action, etc. I am not talking about this.

推荐答案

可以.

typedef void(^MyCustomBlockType)(void);

@interface MyCustomObject {
  MyCustomBlockType block;
}
@property (nonatomic, copy) MyCustomBlockType block; //note: this has to be copy, not retain
- (void) executeBlock;
@end

@implementation MyCustomObject
@synthesize block;

- (void) executeBlock {
  if (block != nil) {
    block();
  }
}

- (void) dealloc {
  [block release];
  [super dealloc];
}
@end

//elsewhere:

MyCustomObject * object = [[MyCustomObject alloc] init];
[object setBlock:^{
  NSLog(@"hello, world!");
}];

[object executeBlock];
[object release];

这篇关于在Objective-C中将引用作为实例var进行阻止的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆