Featured post
iphone - Objective C: retain vs alloc -
i have singleton class code:
manager.h
@interface manager : nsobject { nsstring *jobslimit; nsmutabledictionary *jobtitles; } @property (nonatomic, retain) nsstring *jobslimit; @property (nonatomic, assign) nsmutabledictionary *jobtitles; @implementation manager @synthesize jobslimit; @synthesize jobtitles; + (id)sharedmanager { @synchronized(self) { if(shared == nil) shared = [[super allocwithzone:null] init]; } return shared; } - (id)init { if (self = [super init]) { jobslimit = [[nsstring alloc] initwithstring:@"50"]; jobtitles = [[nsmutabledictionary alloc] init]; } return self; } then in code i'm assigning these variables this:
self.jobslimit = [nsstring stringwithformat:@"%d", progressasint]; [self.jobtitles addentriesfromdictionary:anotherdictionary]; - (void)dealloc { [super dealloc]; [jobslimit release]; [jobtitles release]; } now question code correct? assignment correct?
i'm confused when use alloc and/or retain. need use alloc if property retained? , if use alloc should property assign?
what reference count these variables , dealloc'd/under-dealloc'd when dealloc called?
also singleton classes need initialize ivars in init method above or not have to.
i'd appreciate if can me clear confusion out , in advance.
regards,
your code looks correct, perhaps explanation in order, since sounds you're little unsure.
when assign property has retain semantics using "." syntax, accessor method calls retain. "." syntax shorthand invoking accessor method, so
self.jobslimit = [nsstring stringwithformat:@"%d", progressasint]; is same as
[self setjobslimit:[nsstring stringwithformat:@"%d", progressasint]]; that works out to:
- create (autoreleased) string numeric value
retainstring (you own it) , assignjobslimit
if, on other hand, assign ivar directly (not using "."-accessor), setter method not called. example:
jobslimit = [[nsstring alloc] initwithstring:@"50"]; that is:
- allocate string (you own it), value "50"
- assign jobslimit
either way, own string referred jobslimit, , responsible releasing (e.g., in dealloc method).
- Get link
- X
- Other Apps
Comments
Post a Comment