我有結合的間接指針到一個塊中,並返回供以後分配塊成直接指針,這樣的功能:目標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直接返回新的實例。 –