fischer
fischer

Reputation: 269

Accessing NSMutableArray from inside for loop

I am very new at iOS and objective-c development, so I am struggling with an understanding of how I do this.

First my code:

-(NSMutableArray *)messagesGetList
{  

NSMutableArray *messageList = [[NSMutableArray alloc] init]; 

NSURL *url = [NSURL URLWithString:@"http://xxxx/"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];

AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON)
                                     {    
                                         for (NSDictionary * dataDict in JSON) {

                                             [messageList addObject: dataDict];

                                         }                                             
                                     } 
                                     failure:^(NSURLRequest *request , NSURLResponse *response , NSError *error , id JSON)
                                     {
                                         NSLog(@"Failed: %@", error);        

                                     }];

[operation start];


return messageList;
} 

What I am having a problem with, is that I can not access the NSMutableArray *messageList inside my for (NSDictionary * dataDict in JSON) loop. I.e. nothing is added to the array while executing my loop.

How do I access the array from within my loop?

Thanks in advance for your help, fischer

Upvotes: 1

Views: 570

Answers (3)

Sam
Sam

Reputation: 2579

You should pass a delegate object to this method, and send a message to the delegate when the network request has completed. This is a best practice on the iOS platform.

Upvotes: 0

Caleb
Caleb

Reputation: 124997

Since +JSONRequestOperationWithRequest: takes blocks to be called on success and on failure, it's a good guess that this method runs asynchronously. So, if you're checking the array that's returned from your -messagesGetList right away, it's likely to be empty. If you wait a while before checking, you may see it fill up.

Upvotes: 3

Ian L
Ian L

Reputation: 5591

I think you need to add the __block storage modifier to your NSMutableArray variable, in order for it to be mutable inside the block response.

__block NSMutableArray *messageList = [[NSMutableArray alloc] init]; 

Upvotes: 3

Related Questions