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.
我想将objective-c块存储在属性中以便以后使用。我不知道该怎么做,所以我用谷歌搜索了一下,关于这个主题的信息很少。但我最终还是找到了解决方案,我认为这对像我这样的新手来说是值得分享的。
Initially I've thought that I would need to write the properties by hand to use Block_copy & Block_release.
最初,我认为我需要手工编写属性来使用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.
幸运的是,我发现块是NSObjects, - copy/- release等价于Block_copy/Block_release。所以我可以使用@property (copy)来自动生成setter和getter。
3 个解决方案
#1
132
Edit: updated for 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();
#2
96
Alternatively, without the typedef
另外,没有定义类型
@property (copy, nonatomic) void (^selectionHandler) (NSDictionary*) ;
@ property(复制、原子)空(^ selectionHandler)(NSDictionary *);
#3
9
You can find a very good explanation of this in WWDC 2012 session 712 starting in page 83. The correct way of saving a block under ARC is the following:
你可以在第83页开始的WWDC 2012会议712中找到一个很好的解释。在ARC下保存block的正确方法如下:
@property(strong) my_block_type work;
Be careful with the retain cycles. A good way to solve is set the block to nil when you do not need it anymore:
注意保持周期。一个很好的解决方法是当你不再需要它时,将block设置为nil:
self.work = nil;
#1
132
Edit: updated for 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();
#2
96
Alternatively, without the typedef
另外,没有定义类型
@property (copy, nonatomic) void (^selectionHandler) (NSDictionary*) ;
@ property(复制、原子)空(^ selectionHandler)(NSDictionary *);
#3
9
You can find a very good explanation of this in WWDC 2012 session 712 starting in page 83. The correct way of saving a block under ARC is the following:
你可以在第83页开始的WWDC 2012会议712中找到一个很好的解释。在ARC下保存block的正确方法如下:
@property(strong) my_block_type work;
Be careful with the retain cycles. A good way to solve is set the block to nil when you do not need it anymore:
注意保持周期。一个很好的解决方法是当你不再需要它时,将block设置为nil:
self.work = nil;