I have following class where I have several methods that manipulate with cachedRequests
array
@interface MyClass ()
- (void) sendFromCache:(CacheData*)data;
@end
@implementation MyClass NSMutableArray *cachedRequests; - (void) initialize { cachedRequests = nil; } - (void) processCache { cachedRequests = [self getCachedRequests]; } - (void) sendNext { @synchronized (self) { if (cachedRequests != nil && [cachedRequests count] == 0){ return; } CacheData *data = [cachedRequests objectAtIndex:0]; // <-- here I get Crash if (data != nil) { [cachedRequests removeObject:requestData]; } }
}
@end
Looks like when I call: CacheData *data = [cachedRequests objectAtIndex:0];
some other thread resets cachedRequests
and I get this crash.
So what I did is:
- (void) initialize { @synchronized (self){ cachedRequests = nil; } }
The question are:
- is it enough? Do I need to add
@synchronized (self)
forcachedRequests = [self getCachedRequests];
- is it good practice to use:
@synchronized (cachedRequests)
instead?
Crash details:
2 CoreFoundation 0x18595af68 -[__NSArrayM objectAtIndex:] + 240 (NSArray.m:410)
3 living 0x100c56a1c -[RequestCache sendNext] + 168