Reputation: 8579
I have a lot of blocks in my code. I have a process for initialising a user upon login, I am using Parse.com as my backend:
PFQuery *messageBankQuery = [PFQuery queryWithClassName:@"messageBank"];
[messageBankQuery whereKey:@"username" equalTo:[PFUser currentUser].username];
[messageBankQuery getFirstObjectInBackgroundWithBlock:^(PFObject *object, NSError *error) {
if(!error){
[self setupUserWithMessageBank:object];
}//end no error if
else{
NSLog:(@"error");
}
}];
The messageBank is a parse object that holds references to all the messages the user has. If that object is found setupUserWithMessageBank is called in the block. setupUserWithMessageBank also does more block work:
-(void)setupUserWithMessageBank: (PFObject *)object{
__weak FriendsViewController *weakSelf = self;
//2.)Init the user
weakSelf.currentUser = [[appUser alloc] initWithParseUser:[PFUser currentUser] andMessageBank:object];
//3.) Setup that message array
[weakSelf.currentUser setupMessagedTodayWithHandler:^(BOOL successful) {
if(successful){
//4.)Add friends to the array
[weakSelf.currentUser populateFriendsArrayWithCompletionHandler:^(BOOL successful, NSError *error, BOOL addSelf, BOOL alreadyFriends) {
if(successful){
[self.indicator stopAnimating];
[self.indicator removeFromSuperview];
[self.tableView reloadData];
__weak FriendsViewController *weakSelf = self;
[weakSelf.currentUser refreshMessagesArrayWithCompletionHandler:^(BOOL successful, BOOL newMessages) {
if(successful) {
//set the button
[self.navigationItem.rightBarButtonItem setAction:@selector(showMessages)];
}
else{
[weakSelf displayGeneralError];
}
}];//end fill messages
}
else{
[weakSelf displayGeneralError];
}
}];//end populate method call
}
else{
[weakSelf displayGeneralError];
}
}];
}
I am a little confused over the use of weakSelf. Is it okay to declare weakSelf inside the start of the setupUserWithMessageBank
method? Because his method is called inside another block so technically it's being created inside a block. Do I need to pass weakSelf inside the method instead?
I'm also not completely sure where I should be using weakSelf. Do I need to use it to turn off activity indicators ? Any pointers about my usage of this would be really appreciated. Thanks!
Upvotes: 0
Views: 85
Reputation: 11597
you will probably only need to use a weakSelf if you actually keep a reference to the block within self
(or maybe transitively, a block being kept in an object that is kept within self), which in this case, doesnt look like you are doing. the only reason really to use a weakSelf within a block is to avoid retain cycles.
if both blocks have short life cycles then its probably safe to just use self
within the block. (if you have any control over the life cycle of the blocks, make sure they are set to nil after executing or cleaned up if they dont get executed because of some failure so they dont hang around)
Upvotes: 1