UnderGround
UnderGround

Reputation: 438

How to Pass NSArray Parameter to Completion Block

I want to pass the another NSArray as parameter , to completion block method ,as i am new to this concept, i can not understand the how to do it.Currently i am passing only one array, but now i want to pass second nsarray , in second array i want to pass with array with value so that i can use over there

typedef void(^completion)(NSArray *list);
 -(void) getMoreData:(completion) completion 

Calling Method

[Magento.service getMoreData:^(NSArray *list ) {
        if(list){
                 }

in above method i want to Pass NSArray , this method is in different class and i am calling from different . this array is using in this method .

Upvotes: 2

Views: 2300

Answers (2)

tkanzakic
tkanzakic

Reputation: 5499

You can call it just as a C function, for example, I have declared a new class MyClass. The content of the interface file is:

typedef void(^completion)(NSArray *list);

@interface MyClass : NSObject

- (void)getMoreData:(completion)completionBlock;

@end

and in the implementation

- (void)getMoreData:(completion)completionBlock
{
    // fullfil your array
    NSArray *array = @[@1, @2, @3];

    // call the completion block
    completionBlock(array);
}

and I am using it as follow:

MyClass *myClassInstance = [[MyClass alloc] init];
[myClassInstance getMoreData:^(NSArray *list) {
    if (list) {
        NSLog(@"%@", list);
    } else {
        NSLog(@"Nil array");
    }
}];

and the output is:

2013-05-09 16:29:00.676 Test[823:11303] (
    1,
    2,
    3
)

Upvotes: 4

Marcin Kuptel
Marcin Kuptel

Reputation: 2664

It is not your responsibility to pass an array to the completion block. In the situation you're describing, it is the getMoreData that invokes the completion block so it is that method that passes an array to the block.

- (void) getMoreData: (completion) completion
{
    ...some code...
    NSArray *array = [[NSArray alloc] init];
    if(completion)
        completion(array);

    ...some code...
}

Your responsibility is just to pass a completion block that is going to make use of the array created in the getMoreData method.

Upvotes: 0

Related Questions