Note that there are some explanatory texts on larger screens.

plurals
  1. PORemove object from iterating NSMutableArray
    primarykey
    data
    text
    <p>According to <a href="https://stackoverflow.com/questions/111866/best-way-to-remove-from-nsmutablearray-while-iterating">Best way to remove from NSMutableArray while iterating?</a>, we can't remove an object from NSMutableArray while iterating, yes.</p> <p>But, what if I have a code like the following</p> <pre><code>- (void)sendFeedback { NSMutableArray *sentFeedback = [NSMutableArray array]; for (NSMutableDictionary *feedback in self.feedbackQueue){ NSURL *url = [NSURL URLWithString:@"someApiUrl"]; ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url]; [request setPostValue:[feedback objectForKey:@"data"] forKey:@"data"]; [request setCompletionBlock:^{ [sentFeedback addObject:feedback]; }]; [request startAsynchronous]; } [self.feedbackQueue removeObjectsInArray:sentFeedback]; } </code></pre> <p>I'm using a NSRunLoop to create a NSThread to execute the sendFeedback method every a period of time. The way I sent data to the API is by using <strong>Asynchronous</strong> method (which will create a background thread for each request) Once the feedback has been sent, it has to be removed before NSRunner execute this method at the next period to avoid duplicate data submission.</p> <p>By using asynchronous, the loop (the main thread) will continue running without waiting for the response from server. In some cases (maybe most cases), the loop will finish running before all the response from server of each request come back. If that so, the completion block's code will be execute after the <strong>removeObjectsInArray</strong> which will result in sent data remains in self.feedbackQueue</p> <p>I'm pretty sure that there are several ways to avoid that problem. But the only one that I can think of is using <strong>Synchronous</strong> method instead so that the <strong>removeObjectsInArray</strong> will not be execute before all the request's response are come back (Either success or fail). But if I do so, it's mean that the internet connection has to be available for longer period. The time needed to the sendFeedback's thread will be longer. Even it will be run by newly created NSThread which will not cause the app to not respond, resources will be needed anyways.</p> <p>So, is there any other way besides the one I mentioned above? Any suggestion are welcome.</p> <p>Thank you.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload