mardi 5 mai 2015

Confusion over how I should use weakSelf in blocks

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!

Aucun commentaire:

Enregistrer un commentaire