fab*_*abe 5 objective-c++ clang++
我想将回调块从 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
Run Code Online (Sandbox Code Playgroud)
我了解到这些块存储在堆栈上,如果我想在块创建的范围之外使用它,我必须将其复制到堆(我在示例中没有明确这样做)。我也不确定 ARC 如何处理这种情况。“官方”允许这样做吗?我正在使用 Xcode 9.2。