Ilesh P
Ilesh P

Reputation: 4036

perform selector does not cancel second times

In my Application I am using perform selector for update messages form server. i call this method in viewWillAppear.
Example UpdateMessages Method call in viewWillAppear and set perform selector in web service response like this.

    -(void)UpdateChatMessage {
/* set some parameters here */
        [[UAAPIMaster sharedMaster] getUpdateMessageCall_Completion:params :^(id returnData) {
               [self performSelector:@selector(UpdateChatMessage) withObject:nil afterDelay:1.2]; // Call this method again using performSelector
            }
        }];
    }

The problem is when I Pop this view i want to stop this cycle. so I put the code in viewWillDisappear.

-(void)viewWillDisappear:(BOOL)animated {
   [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(UpdateChatMessage) object:nil];
    [super viewWillDisappear:animated];
}

But it is working only first time second time I enter this view the selector working perfectly but it does not stop. it working background. so please help me to solve this problem. and I want to know why this problem occur. Thanks In advanced.

Upvotes: 0

Views: 362

Answers (2)

iOSX
iOSX

Reputation: 1300

My guess is that the completion handler in your code is executed asynchronously, so it may happen that it is executed after the view controller is already removed. You could try to avoid that by ensuring that performSelector is only called if the view is still available:

@property BOOL shouldPerformUpdateChat;

-(void)UpdateChatMessage {
/* set some parameters here */
    [[UAAPIMaster sharedMaster] getUpdateMessageCall_Completion:params :^(id returnData) {
        dispatch_async(dispatch_get_main_queue(), ^{
           if ( self.shouldPerformUpdateChat ) {
               [self performSelector:@selector(UpdateChatMessage) withObject:nil afterDelay:1.2]; // Call this method again using performSelector
           }
        });
   }];
}

-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.shouldPerformUpdateChat = YES;
    [self UpdateChatMessage];
}

-(void)viewWillDisappear:(BOOL)animated {
    self.shouldPerformUpdateChat = NO;
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(UpdateChatMessage) object:nil];
    [super viewWillDisappear:animated];
}

Upvotes: 1

Abhinav
Abhinav

Reputation: 38162

Per Apple Documentation:

Discussion All perform requests are canceled that have the same target as aTarget, argument as anArgument, and selector as aSelector. This method removes perform requests only in the current run loop, not all run loops.

So, you might be running on different run loops in creation and cancellation.

As a side note, I also want you to check by passing self instead of nil in object parameter:

[NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(UpdateChatMessage) object:self];

Upvotes: 2

Related Questions