Salx
Salx

Reputation: 589

Assign code blocks to a property objective c

I'm attempting to get Background App Refresh going in my iOS application. However, I'm having some trouble understanding code blocks.

I've done some research on it, and would say I have a beginner's understanding so far. The method in question is:

-(void)application:(UIApplication *)application performFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler{

This method wants a UIBackgroundFetchResult return type. Due to the complexity of my application though, I cannot return that with ease. There's a lot that happens when pulling data from the internet in Background mode.

In the body of that method, I have a custom method that also has a completion block. What I'm trying to do is define another custom method in my code that would be assigned to the completion handler.

In my data manager, I have a property defined as :

@property (copy, nonatomic) void (^fetchCompleted)(UIBackgroundFetchResult);

In the performFetchWtihCompletionHandler method implementation, I call on my data manager:

-(void)fetchNewDataWithCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler{
    _fetchCompleted = completionHandler;

    _state = DMSMT_WaitingForPartnerData;
    [self getActiveQueues];
}

Once my downloads are completed, I call on the fetchCompleted method:

[self fetchCompleted];

Herein lies my problem. I need to pass a UIBackgroundFetchResult argument, but I see no way to do that. I tried [self fetchCompleted:UIBackgroundFetchResultNewData]; but it yells at me.

Any ideas?

Thanks in advance.

EDIT:

Here was the fix. So simple!

if(_fetchCompleted != nil){
    [self fetchCompleted](UIBackgroundFetchResultNewData);
}

Upvotes: 1

Views: 442

Answers (2)

Tommy
Tommy

Reputation: 100652

This method wants a UIBackgroundFetchResult return type

No, it wants a void return type. One of the parameters is of type UIBackgroundFetchResult. Parameters are not return results. UIBackgroundFetchResult is just a type of variable.

Which appears to flow into your error. [self fetchCompleted] is the getter that will return the fetchCompleted variable. It doesn't do anything with it.

To perform a block, use function-like syntax. E.g. [self fetchCompleted]().

Upvotes: 1

Justin Moser
Justin Moser

Reputation: 2005

You are treating fetchCompleted as a method but it is a block! Try this out:

-(void)getActiveQueues {
    // Do some work here
    // When you are finished...

    // Set the appropriate result
    UIBackgroundFetchResult result;

    // Check to make sure fetchCompleted is not NULL
    if (self.fetchCompleted) {
        // Invoke the block!
        self.fetchCompleted(result);
    }
}

Upvotes: 3

Related Questions