I have a function that binds an indirect pointer into a block, and returns the block for later assignment into the direct pointer, like this:
@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);
}
The problem is that while this all compiles and runs, the action of the block is forgotten immediately when the block returns. The printout of running [iWillNotDoWhatImSupposedTo] is:
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
Any insights for how I can make this callback work?