Search code examples
objective-creturnnsarrayobjective-c-blocks

Return NSArray function from asynchronous BLOCK


I have a function that must have this signature and must return an array of Test objects

+ (NSArray <Test *>*_Nullable) getAllDetails

Within the function I am doing a GET request using RESTKIT asynchronously which fetches the data succesfully from a remote REST API and saving to an array which I return here. Because the function returns before the block has executed when I call the class somewhere else with [MyClass getAllDetails]; function my array of Test objects is nil however when I log within the call the array is populated. Been a while i've done some OJB-C and blocks for that matter.


Solution

  • This is a wrong approach if you are fetching the data asynchronously you should use the block approach or create delegate method to handle the response.

    You can try block approach like this

    //Declare your block like this in your class
    typedef void (^GetAllRequestBlock)(NSArray <Test *>*_Nullable);
    

    And Use it in your function like :-

    + (void)getAllDetails:(GetAllRequestBlock)completionHandler{
        BOOL response = true; // Your api response check
        if (response) {
            if completionHandler{
                completionHandler(Array); // Pass your array custom array that you've defined in the block
            }
        }else{
            if completionHandler{
                completionHandler(nil);
            }
        }
    }