Reputation: 27
I'm calling my DatabaseManager to save an object created in a viewController like so:
[DatabaseManager addUniqueObject:fooChild key:[fooParent fooChildKey] toObject:self.foo callback:^(BOOL succeeded, NSError *error) {
if (error) {
[[UIApplication sharedApplication] endBackgroundTask:self.sendBackgroundTaskId];
return;
}
[self.tableView reloadData];
[self scrollToBottomAnimated:YES];
}
[[UIApplication sharedApplication] endBackgroundTask:self.sendBackgroundTaskId];
}];
addUniqueObject
is a class method in my DatabaseManager (I'm using Parse as the backend as you can see):
+ (void)addUniqueObject:(PFObject*)uniqueObject key:(NSString*)key toObject:(PFObject*)object callback:(void(^)(BOOL succeeded, NSError *error))callback {
if (uniqueObject) {
[PFCloud callFunctionInBackground:@"addUniqueObjectToObject"
withParameters:@{@"classKey":[object parseClassName],
@"objectId":[object objectId],
@"keyToAdd":key,
@"objectToAddClassKey":[uniqueObject parseClassName],
@"objectToAddId":[uniqueObject objectId],
}
block:^(NSMutableDictionary *results , NSError *error) {
if (!error) {
callback(YES, error);
}
else {
callback(NO, error);
}
}];
}
}
First question - So if I create this object but then navigate away and thus pop this VC before the save executes, then self.tableView
or any other property I'm referencing in the completion block is nil
at this point, correct?
Second question - I passed the completion block to the DatabaseManager - does this completion object still exists if the original VC is destroyed? Do I have to check for existence of this block before I execute callback()
?
This doesn't seem to cause any problems for me, so I hadn't questioned it until now. But I'd like to understand.
Upvotes: 0
Views: 712
Reputation: 3397
No, your VC won't be deallocated because self
is captured inside block. If you want it to be deallocated, you should write something like this:
__weak typeof(self) weakSelf = self; // we don't increase retain count here
[DatabaseManager addUniqueObject:fooChild key:[fooParent fooChildKey] toObject:self.foo callback:^(BOOL succeeded, NSError *error) {
__strong typeof(self) self = weakSelf;
// if weakSelf is still not deallocated, it will be retained until block finishes
consider using @strongify/@weakify instead of this code snippet.
Yes it is. callback
is retained by block you passing to callFunctionInBackground:withParameters:block:
, so it won't be released until block is executed. If you are sure that noone will call yout function with callback:nil
, then you don't need to check it's still exists in completion block.
Upvotes: 1