0

I am building a simple messaging app using Parse's framework. I have a method called displayMessages. This is called each time the phone receives a push.

However, as this message is doing work in the Parse database I don't want to call it again if it's already running. I want to wait until it is finished and then call it.

I am using the following code:

-(void)receivedPush
{

    [self displayMessages];

}

and:

-(void)displayMessages
{
 //code here
}

If received push is called I want it to wait until displayMessages is finished before calling it. In displayMessages I have a Parse call:

[PFObject deleteAllInBackground:toDelete block:^(BOOL succeeded, NSError *error) {

                    }];

It's actually this that I need to wait for, deleteAllInBackground. How can I get around this? I tried using NSOperation queue and that's fine for queuing displayMessages but this won't give my app the desired result because although displayMessages finishes execution at some point it still has deleteAllInBackground running.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Kex
  • 8,023
  • 9
  • 56
  • 129

1 Answers1

0

If I understand correctly, your requirement is that you only want one "instance" of displayMessages running at one time. What you are asking to do is make displayMessages "threadsafe" What you should do is wrap the code in displayMessages inside @synchronized tags.

What does @synchronized() do?

https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/Multithreading/ThreadSafety/ThreadSafety.html

Alternately, you could create some kind of queueing system that uses flags, so recievedPush would actually add the push to a queue and there would be some kind of timer loop that calls display messages repeatedly but only fires when it is done processing.

Edit in response to comment Create a manual "operation queue" that does what you want it to

- (void) methodThatRunsWhenFiredByTimer {
    if (self.flag) {
        [self displayMessages];
    }
}

- (void) displayMessages {
    PushData *data = [self dequeueData]; //maybe, not sure how you're accessing the push data
    self.flag = NO;
    //Code Here
    [PFObject deleteAllInBackground:toDelete block:^(BOOL succeeded, NSError *error) {
        //Code Here...
        self.flag = YES;
    }];
}

- (void) recievedPush:(Pushdata) data {
    [self enqueuePushData:data];
}
Community
  • 1
  • 1
Pinwheeler
  • 1,061
  • 2
  • 13
  • 26
  • displayMessages has the deleteAllInBackground method call. so displayMessages will finish executing but it will still be deleting objects in the background. I don't want to call it again until the background work is finished. That's the reason I can't queue it in NSOperationQueue.. – Kex Jan 22 '15 at 16:11
  • @Kex made an edit, not sure if this is what you are talking about though – Pinwheeler Jan 22 '15 at 16:27