Reputation: 329
I created an object with a NSDate
property like this:
MyClass.h
@interface MyClass: NSObject { NSDate *date_ }
@property (nonatomic, retain) NSDate *date;
MyClass.m
@implementation MyClass
@synthesize date=date_;
-(id) init
{
if (self=[super init])
date_ = [NSdate date];
return self;
}
-(void) dealloc
{
[date_ release];
date_ = nil;
}
But when I create this object
[[[MyClass alloc] init] autorelease];
I get an EXC_BAD_ACCESS
when my thread calls objc_release
:
If I add a retain on init:
-(id) init
{
if (self=[super init])
{
date_ = [NSdate date];
[date_ retain];
}
return self;
}
It seems to be working fine, but isn't declaring the property with "retain" supposed to retain it for me ?
Upvotes: 0
Views: 207
Reputation: 4520
By using date
(the Ivar) you circumvent the setters' retain - which is what you would do in your init method (don't use setters/getters in init but access iVar directly).
Since [NSDate date]
returns an autoreleased object, you have to retain it.
To use the setter you would need to call the setter method (either self.date
or [self setDate:]
). In this case the object gets retained by the setter automatically.
Do this everywhere except in your init and dealloc.
Also I guess there is a typo since in your init you use date
as iVar where it should be date_
as defined by your synthesize. this has been edited to be now correct in the OP
Upvotes: 2