So I’m trying to write an initializer for a subclass of NSOperation. This is my first time using NSOperation. My NSOperation subclass looks like this:
.h
@property (nonatomic, copy) NSString *fileName;
.m
@synthesize fileName = _fileName;
- (id)initWitFileName:(NSString *)fileName {
if (self = [super init]) {
_fileName = fileName;
}
return self;
}
- (void)dealloc {
[_fileName release];
[super dealloc];
}
- (void)main {
// do long task
}
So I thought when I create my own initializers, I should just set the ivar myself since the state of the object is undetermined in the init method. So I don’t use the accessor in the initializer. When my main method gets run, I get a memory bad access and a crash. However, in my init method, if I do this instead:
- (id)initWitFileName:(NSString *)fileName {
if (self = [super init]) {
_fileName = [fileName retain];
}
return self;
}
I do not get a crash. What is correct? I’d think in this second case that I wouldn’t be releasing the memory since the accessor is (copy). Or is it because I don’t use the accessor, that my fileName object basically gets dealloc’d only since there is no +1 in the initWithFileName method? Thanks!
When you
@synthesizesomething with a set of properties, you’re generating getters and setters for the object. This allows you to use methods likeor
Both of the lines above function in exactly the same way, and might be implemented like this:
This implementation is overly simplified. See idz’s comment below for a better understanding of the logic that a real setter would use.
In your example above, you’re simply using the
=operator, and not a generated function.Because of this, you’re simply setting the address of
_fileNametofileName. None of yoursynthesizeproperties matter, and don’t make a difference here.Your explanation:
is exactly correct. To properly replicate the
copyproperty used by your synthesizer, use this: