Colton Anglin
Colton Anglin

Reputation: 451

Problems with making a completion block [iOS]

I am trying to code a method with a completion block that returns the gathered data. I'm not sure if I'm just not doing it right or something else is the matter.

My method:

-(void)getAllUserDataWithUsername:(NSString *)username completion:(void (^)(NSDictionary     *))data {

I want to be able to set the NSDictionary to the recieved data and be able to get that data when I call this method somewhere.

Thanks!

Upvotes: 0

Views: 258

Answers (1)

Danny S
Danny S

Reputation: 1291

There is a slight change to make for your declaration to be cleaner. data should be the name of the NSDictionary parameter and not the completion block name.

A step by step guide to declare, implement and call a method with a completion block would be as follows:

In your class header that implements the method you can declare the method:

- (void)getAllUserDataWithUsername:(NSString *)username 
                        completion:(void (^)(NSDictionary* data))completion;

Notice how data is the parameter passed in the block and completion is the name of the block.

In the implementation of your class you can do:

- (void)getAllUserDataWithUsername:(NSString *)username 
                        completion:(void (^)(NSDictionary* data))completion {
    // your code to retrieve the information you need
    NSDictionary *dict = //the data you retrieved
    // call the completion block and pass the data
    completion(dict); // this will be passed back with the block to the caller
}

Now in wherever you call this method you can do:

[myClass getAllUserDataWithUsername:@"username" completion:^(NSDictionary *data) {
    // data will be `dict` from above implementation
    NSLog(@"data = %@", data);
}];

Hope it helps.

Upvotes: 1

Related Questions