Releasing an object with NSDate object as property

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 ?

Answers


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


Need Your Help

Get Theme and Wordpress version details via API

wordpress wordpress-theming wordpress-plugin-dev

wordpress gives API for all plugins including change log , version , details, screenshots..etc in http://codex.wordpress.org/WordPress.org_API

Optimized pseudo code for D*Lite

algorithm d-star

I'm looking at the optimized version of the

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.