I have following class where I have several methods that manipulate with cachedRequests
array
MyClass.h
@interface MyClass : NSObject {
NSMutableArray *cachedRequests;
}
+(MyClass*) instance; //Singleton
MyClass.m
@interface MyClass ()
- (void) sendFromCache:(CacheData*)data;
@end
@implementation MyClass
static MyClass *sharedSingleton = nil;
+(MyClass*) instance{
@synchronized(self) {
if(sharedSingleton == nil)
sharedSingleton = [[super allocWithZone:NULL] init];
}
return sharedSingleton;
}
- (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