【发布时间】:2016-11-17 17:44:01
【问题描述】:
我有一个函数将间接指针绑定到块中,并返回块以供以后分配给直接指针,如下所示:
@interface SomeClass : NSObject
@property int anInt;
@end
@implementation SomeClass
@end
typedef void(^CallbackType)(int a);
- (CallbackType)getCallbackToAssignTo:(SomeClass **)indirectPointer {
return ^(int a){
NSLog(@"indirectPointer is: %p", indirectPointer);
NSLog(@"*indirectPointer is: %p", *indirectPointer);
(*indirectPointer) = [[SomeClass alloc] init];
(*indirectPointer).anInt = a;
NSLog(@"After: indirectPointer is: %p", indirectPointer);
NSLog(@"After: *indirectPointer is: %p", *indirectPointer);
};
}
- (void)iWillNotDoWhatImSupposedTo {
SomeClass *directPointer = nil;
CallbackType cb = [self getCallbackToAssignTo:(&directPointer)];
NSLog(@"directPointer is pointing to: %p", directPointer);
NSLog(@"&directPointer is pointing to: %p", &directPointer);
cb(1);
NSLog(@"after callback directPointer is: %p", directPointer);
NSLog(@"after callback &directPointer is: %p", &directPointer);
}
问题是,虽然这一切都编译并运行,但当块返回时,块的操作会立即被遗忘。运行[iWillNotDoWhatImSupposedTo]的打印输出是:
directPointer is pointing to: 0x0
&directPointer is pointing to: 0x7fff5ce1d060
--- callback execution starts here
indirectPointer is pointing to: 0x7fff5ce1d050
*indirectPointer is pointing to: 0x0
After assignment: indirectPointer is pointing to: 0x7fff5ce1d050
After assignment: *indirectPointer is pointing to: 0x61800001e1d0
--- callback returns here, and the contents of the pointer is lost
after running callback directPointer is pointing to: 0x0
after running callback &directPointer is pointing to: 0x7fff5ce1d060
关于如何使此回调起作用的任何见解?
【问题讨论】:
-
不确定这是怎么发生的,但我觉得有趣的是直接指针所在的地址与indirectPointer的地址不同(分别以60和50结尾)
-
大概在您的真实代码中,您正在传递要设置的 ivar 的地址?否则,您应该让 Block 直接返回新实例。
标签: objective-c objective-c-blocks objective-c-runtime