lagos
lagos

Reputation: 1968

Trouble adding a custom object to NSMutableArray inside a block

I'm sending some custom objects to a server from the app with ASIFormDataRequest inside a dispatch_async block. And when I receive OK from the server I need to put the object in a NSMutableArray. But when I try to access the the array from outside the block is empty.

My code pseudocode is like this:

  -(void)sendObjects{
      NSMutableArray *sendedObjects = [NSMutableArray alloc]init];
      NSMutableArray *objectsToSend = [NSMutableArray alloc]init];

     for(ObjectSend *obj in objectsToSend){
           dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0),^{

           ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
           [request addRequestHeader:@"Content-Type" value:@"application/json"];
           [request appendPostData:[NSJSONSerialization dataWithJSONObject:sendDictWithObjects options:NSJSONWritingPrettyPrinted error:&error]];
           [request startSynchronous];
           NSError *requestError = [request error];
           if(!requestError){
                NSString *response = [request responseString];

                obj.sended = YES;
                [sendedObjects addObject:s];

            }

          });
      }
      NSLog(@"%i",sendedObjects.count);

  }

And at the end the sendedObjects array is empty. I am using ARC, so can't retain. Somebody can help me?

Upvotes: 0

Views: 816

Answers (1)

lawicko
lawicko

Reputation: 7344

Your request may be synchronous, but you dispatch them from the blocks that are scheduled for concurrent execution. This means that the NSLog statement can be reached before any of you requests are dispatched. You have two options to fix your problem:

  1. Don't use dispatch_async and blocks, just simply send the requests inline. I wouldn't recommend this if the code that you showed runs on main thread.
  2. Register for completion callbacks and check your array of objects then. You can see how this can be done here in the completion callbacks section

By the way, the past form of send is sent.

Upvotes: 1

Related Questions