我有结合的间接指针到一个块中,并返回供以后分配块成直接指针,这样的功能:目标C间接指针未能更新直接指针
@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直接返回新的实例。 –