0

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?

lagos
  • 1,968
  • 3
  • 17
  • 26

1 Answers1

1

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.

lawicko
  • 7,246
  • 3
  • 37
  • 49
  • I did it synchronous and it work find. Then I saw that the dispatch queue only had a default priority, and it happens what you said, that the NSLog is reached before the block. Thanx for the grammatically lesson, difficult when I am working in 3 different language. – lagos Apr 12 '12 at 12:35