Reputation: 12499
I have an NSMutableArray
where I add a set of custom objects. I'm also using the location service, and whenever locationManager:didUpdateLocations:
, I check that array to perform some operations with the appropriate object, which is one of the objects of the array. On the other hand, I need to update such array every few minutes, so I guess this could cause a conflict if the array is getting updated while it is being read.
What should be the best way to handle this scenario in iOS?
Thanks!
Upvotes: 2
Views: 116
Reputation: 114875
There are a couple of approaches you can take.
The first is for your reader thread to copy the property value into a local variable and for your update method to manipulate a copy of the array (or create a new array) and then set the property to the updated/new array. This will ensure that the reader method continues to operate with the old data until its next execution. Something like this -
-(void)readerMethod {
NSMutableArray *myData=self.myArrayProperty;
// You can now operate safely on myData
}
-(void)updateLocations {
NSMutableArray *myData=[self.myArrayProperty copy];
// manipulate myData
self.myArrayProperty=myData;
}
The second approach is to use @synchronized
-(void)readerMethod {
@synchronized(self.myArrayProperty) {
// Array operations
}
}
-(void)updateLocations {
@synchronized(self.myArrayProperty) {
// manipulate myData
}
}
The first method can incur greater memory overhead and time to copy the array (this is significant if the array is large). The second can block your main thread, so you can have UI performance issues, but this is probably not going to be an issue and is the approach I would recommend.
Upvotes: 1