【发布时间】:2018-03-01 05:05:06
【问题描述】:
我想将一个回调块从我的 Objective-C++ 代码传递给一个 C++ 对象。这非常简单,因为我可以将块分配给 std::function。在我的迷你示例中,一切正常,但我仍然不确定这样做是否安全。
#import "ViewController.h"
#include <functional>
std::function<void(void)> f;
@interface T : NSObject
@property (strong) NSString* value;
@end
@implementation T
- (void)dealloc {
NSLog(@"dealloc");
}
@end
@implementation ViewController
- (IBAction)storeBlock:(UIButton *)sender {
T* t = [[T alloc] init];
t.value = @"the captured obj";
f = ^void(void) { NSLog(@"This is the block with %@", t.value); };
}
- (IBAction)useBlock:(UIButton *)sender {
f();
}
- (IBAction)releaseBlock:(UIButton *)sender {
f = nullptr;
}
@end
我了解到这些块存储在堆栈中,如果我想在块的创建范围之外进一步使用它,我必须将它复制到堆中(我在我的示例中没有明确地这样做) .我也不确定ARC如何处理这种情况。是否“官方”允许这样做?我正在使用 Xcode 9.2。
【问题讨论】:
标签: objective-c++ clang++