How to return method object from inside block iOS

Return type of method is NSArray, so when I call this method I get nil or empty array. Here it's below my method implementation:

- (NSArray *)startParsing { __block NSArray *array; allProductsID = [[NSMutableArray alloc] init]; NSString *string = [NSString stringWithFormat:@"http://%@:@%@",kPrestaShopAPIKey, kPrestaShopURLString]; NSURL *url = [NSURL URLWithString:string]; AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:url]; manager.responseSerializer = [AFXMLParserResponseSerializer serializer]; [manager GET:@"categories/21" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) { NSXMLParser *parser = (NSXMLParser *)responseObject; [parser setShouldProcessNamespaces:YES]; parser.delegate = self; [parser parse]; //NSLog(@"First response %@", responseObject); for (int i = 0; i< [[self.xmlShop objectForKey:@"product"] count]; i++) { //NSLog(@"Second ID --> %@", [self.xmlShop objectForKey:@"product"][i]); NSString *productID = [NSString stringWithFormat:@"products/%@", [[self.xmlShop objectForKey:@"product"][i] objectForKey:@"id"]]; [allProductsID addObject:productID]; } array = [allProductsID copy]; } failure:^(AFHTTPRequestOperation *operation, NSError *error) { NSLog(@"Error occured %@", [error localizedDescription]); }]; return array; }

Can anyone help me with this problem?

-------------Problems Reply------------

As Quentin already mentioned, you can not directly do that because you are internally performing an asynchronous request. That means that your program starts the request and then continues its next statements and does not wait for the request to finish. What you should do is either

  • make the request synchronous to cause the program to wait until the request has finished. Be carefull however to not call this method from the main thread since that would block your app from continuing to respond until the request returned. Or
  • use a block as callback for the startParsing method (the same way blocks are used for the actual request callbacks)

That would loke for example like the following:

- (void)startParsing:(void (^)(NSArray*))parsingFinished {
allProductsID = [[NSMutableArray alloc] init];
NSString *string = [NSString stringWithFormat:@"http://%@:@%@",kPrestaShopAPIKey, kPrestaShopURLString];
NSURL *url = [NSURL URLWithString:string];

AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:url];
manager.responseSerializer = [AFXMLParserResponseSerializer serializer];

[manager GET:@"categories/21" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
// do your parsing...
parsingFinished([allProductsID copy]);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
parsingFinished([[NSArray alloc] init]);
// or return nil or provide a parsingFailed callback
}];
}

which you would then call like

[yourObject startParsing:^(NSArray *parsedData) {
// do something with the parsed data
}];

You can't.
In your case, the block is executed asynchronously. It means that your method may already have returned when the block is executed.

You need to call another method or send a NSNotification from your blocks to pass your array.

Category:ios Views:1 Time:2018-06-11

Related post

  • Ajax enabled WCF service. How to return complex object from service call? 2011-09-05

    Ajax enabled WCF service. How to return complex object from service call? It fails when try to return any complex object that is not primitive like int, string .etc. Is it possible at all? I can't find any sample. All samples are with primitive signa

  • Why can't I return an object from my block? 2011-12-08

    I'm trying to return a NSMutableArray from my block in my method, but when I add the line return [responseString JSONValue];, I get some compiler warnings. - (NSMutableArray*)getTodayData:(NSDate*)today { ASIFormDataRequest *request = [[[ASIFormDataR

  • How to return collection objects from c# and Access them in c++? 2009-06-28

    i have tried returning a collection of objects from c# and access them usig c++ via COM but failed.I have tried for List ArrayList and IDictionary all and failed. i have tried http://stackoverflow.com/questions/1032060/how-to-return-a-collection-of-s

  • How to return partial view from inside the HtmlHelper? 2011-02-10

    I have the following code: public static PartialViewResult DateTime(this HtmlHelper helper) { return System.DateTime.Now.ToLongTimeString(); } and now I want to return a Partial view from inside the DateTime method. But helper instance does not have

  • How to return a value from inside an interator in Javascript 2011-01-26

    I have a function that I want to return true or false. Inside the function I iterate through some elements on the page and check their values. But if I put a return statement inside the iterator, it will return from the anonymous function right? (and

  • How to return an object from two tables form a rails web serivce? 2011-02-23

    I have two ActiveRecord models: Event and Place. Event has a property name place_id which points to Place. Place has a column named place_name. How do I write a web service that returns a json of events with each event also holds the associated place

  • Object not loaded due to lazy loading. How to return all objects from BLL 2012-01-21

    I'm having a bit of trouble figuring out how to make this repository pattern work. In a nutshell, my solution looks something like this... ASP.Net MVC ^ | Business Logic ^ | Data Access (Repositories and Unit of Work) ^ | Entity Framework Models I ha

  • How to return an object from a recursed function? 2011-12-12

    I'm needing to go through all the controls on a page, looking for a specific one. We've got a bunch of user controls, a masterpage, content panel, &c. The basic idea is simple, but once I find the control I want, say five 'layers' in, the control

  • How to return an object from an IntentService? 2011-08-24

    My Activity starts an IntentService that then calls a remote API. I then need to pass the resulting data back to the Activity (through a BroadcastReceiver). Within much of the rest of the app this data is encapsulated in a single class, with primitiv

  • How to return an object from a selector? 2014-09-23

    I have a code $( document ).ready(function() { $('#boxone') = new Category(); $('#boxone').playFunction(); foo(); }) function Category(el) { this.playFunction() { alert('bar') } } function foo() { $('#boxone').playFunction() } This first playFunction

  • What if I need to return an object from thread's runnable object? 2011-02-27

    What I need is to return token object as a result of adapter.authenticate() operation placed in thread. Have no idea how to return an object from there, please advice. Thank you. public Token authenticate(final String email, final String password) {

  • How to access the value of an object from inside a method of the same object in Javascript? 2009-11-30

    I'm trying to add a toBool() "method" inside the Object object using prototype... something like this: Object.prototype.toBool = function () { switch(this.toLowerCase()) { case "true": case "yes": case "1": return true; case "false": case "no": case

  • How to return Json object to view in a Async method 2011-02-28

    I have ASP.NET MVC 2 web app. On page load I call a javascript method: function getSomeData() { $.post(GetTablesDataUrl, null, function (data) { alert(data); }); } here is then called a method in my HomeController.cs public void GetTablesData() { Web

  • How to return optional information from methods? 2011-06-24

    The general question is how to return additional information from methods, beside the actual result of the computation. But I want, that this information can silently be ignored. Take for example the method dropWhile on Iterator. The returned result

  • How do I return an object from a dialog when using WindowManager in Caliburn Micro 2011-11-01

    I'm just starting out with the Caliburn Micro WindowManager. I have managed to display a modal dialog containing my WPF view. I need to return an object from the dialog. What is the best way to do this? Background - this is a login dialog. I need to

  • Node.js: How to properly return an object from within a callback? 2012-01-04

    Still wrapping my head around callbacks. What's the proper way to define/return an object from within a callback function? You can see my 2 console.logs in the following snippet, the one outside of the callback is of course undefined, how do I define

  • A method/property in a parent class returning an object from a child class 2012-04-15

    This may well be a stupid question, but here it goes anyway. In objective c, in an initiation method of a child class one often sets self=[super init]. Now, self is of the child class, and no conversion is required, which means (or not..) that the in

  • How to grab the view object from inside a Zend_Controller_Plugin Class? 2009-09-18

    I need to make a Zend Controller Plugin that repopulates a form with a request that is in every page on predispatch. just need to figure how to grab the view object from inside the plugin and if there are any specifics for plugins as far as file dire

  • Calling a method in an object, from inside a different object? 2010-02-15

    Is there anything particularly bad about doing something like this in Javascript: myapp.someObject = { this.doSomething = function() { // stuff happens . . . // myapp.someOtherObject.doSomething(); } } ...That is to say, calling a method in another o

  • How to create Bitmap object from a Graphics object? 2010-06-11

    How to create Bitmap object from a Graphics object ? I would like to read pixels from my Graphics object. for example, like, System.Drawing.BitMap.GetPixel(). I am trying to find out empty area (all white, or of any colour) inside a pdf document, to

  • How to deserialize multiple objects from a json stream? 2012-01-16

    Ok, I have asked questions about something like this before, but this is a different subject, so i feel i should make a new topic about it. I'm sorry if this is something i should not have done... Anyway: I'm currently reading a twitterfeed and tryin

  • How to prevent an object from getting garbage collected? 2009-08-25

    Please help me How to prevent an object from getting garbage collected is there any approaches by finalize or phantom reference and is there any other approaches? UPDATED:I was asked a ques in an interview he was referring something can be done in fi

  • How to return an array from jQuery ajax success function properly? 2010-02-03

    This question already has an answer here: How to return the response from an asynchronous call? 6 answers TheObject = { getArray: function(){ var groups = new Array; $.ajax({ type: "POST", url: "link.php", success: function (data){ var counter = 0; $

  • How to return Generic.List from a function in C# 2010-12-10

    ASP.NET 3.5 C# I am joining two tables using Linq. Table names are MapAssets and ExitPoint. In Database they are related with 'has a relationship' I am writing a function in my BLL to return the joined table public List<ExitPoints> GetExitPoint

  • How to return the results from a Mysqli prepared statement 2011-05-01

    Im studying Mysqli at the moment. But i have a problem about how to return a resultset from a mysqli prepared statement. I have the following code in Loginclass.php: $stmt = mysqli_stmt_init($db->getCon()); $stmt->prepare('SELECT * FROM `user`

Copyright (C) dskims.com, All Rights Reserved.

processed in 0.270 (s). 11 q(s)