ios - Objective-C calling instance method within Singleton -
i created singleton class named datamanager
. i've set caching. however, when attempting call cache instance methods within instance method of datamanager
, i'm getting exc_bad_access
error on line:
nsmutablearray *stops = [[datamanager sharedinstance] getcacheforkey:@"stops"];
datamanager.h
@interface datamanager : nsobject { fmdatabase *db; nsmutabledictionary *cache; } + (datamanager *)sharedinstance; // ... more methods - (id)getcacheforkey:(nsstring *)key; - (void)setcacheforkey:(nsstring *)key withvalue:(id)value; - (void)clearcache;
datamanager.m
- (nsarray *)getstops:(nsinteger)archived { nsmutablearray *stops = [[datamanager sharedinstance] getcacheforkey:@"stops"]; if (stops != nil) { nslog(@"stops: %@", stops); return stops; } stops = [nsmutablearray array]; // set stops... [[datamanager sharedinstance] setcacheforkey:@"stops" withvalue:stops]; return stops; }
it seems occur when called view controller. first view controller no error, second view controller, error.
this first attempt @ singleton, i'm sure making simple mistake. failing see myself.
note: i've tried [self getcache...]
same result.
update
here singleton implementation. adapted http://www.galloway.me.uk/tutorials/singleton-classes/
+ (datamanager *)sharedinstance { @synchronized(self) { if (!instance) { instance = [[super allocwithzone:null] init]; } } return instance; } + (id)allocwithzone:(nszone *)zone { return [[self sharedinstance] retain]; } - (id)copywithzone:(nszone *)zone { return self; } - (id)retain { return self; } - (unsigned)retaincount { return uint_max; } - (oneway void)release { // never release } - (id)autorelease { return self; } - (id)init { if (self = [super init]) { if (db == nil){ bourbonappdelegate *appdelegate = (bourbonappdelegate *)[[uiapplication sharedapplication] delegate]; [appdelegate createeditablecopyofdatabaseifneeded]; db = [[fmdatabase alloc] initwithpath:[appdelegate getdbpath]]; } if (![db open]) { nsassert(0, @"failed open database."); [db release]; return nil; } [db settraceexecution:yes]; [db setlogserrors:true]; cache = [nsmutabledictionary dictionary]; nslog(@"cache: %@", cache); } return self; }
your cache
object autoreleased, it's no longer in memory when try access it.
use [nsmutabledictionary alloc] init]
instead of [nsmutabledictionary dictionary]
instance retained.
Comments
Post a Comment