如何在Objective-C的属性中存储块? [英] How to store blocks in properties in Objective-C?

查看:79
本文介绍了如何在Objective-C的属性中存储块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将Objective-C块存储在一个属性中,以备后用.我不确定该怎么做,所以我在Google上搜索了一下,关于该主题的信息很少.但是我最终设法找到了解决方案,并且我认为对于像我这样的其他新手来说,也许值得分享.

I'd like to store objective-c block in a property for later use. I wasn't sure how to do it so I googled a bit and there is very little info about the subject. But I've managed to find the solution eventually and I've thought that it might be worth sharing for other newbies like me.

最初,我认为我需要手动编写属性才能使用Block_copy& Block_release.

Initially I've thought that I would need to write the properties by hand to use Block_copy & Block_release.

幸运的是,我发现

Fortunately I've found out that blocks are NSObjects and - copy/- release is equivalent to Block_copy/Block_release. So I can use @property (copy) to auto generate setters & getters.

推荐答案

已针对ARC更新

typedef void(^MyCustomBlock)(void);

@interface MyClass : NSObject

@property (nonatomic, copy) MyCustomBlock customBlock;

@end

@implementation MyClass

@end

MyClass * c = [[MyClass alloc] init];
c.customBlock = ^{
  NSLog(@"hello.....");
}

c.customBlock();

这篇关于如何在Objective-C的属性中存储块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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