0

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 ?

Vineet Singh
  • 4,009
  • 1
  • 28
  • 39
Amit Farkash
  • 329
  • 3
  • 16
  • [AT]property (nonatomic, retain) will retain if you do self.date = [NSDate date] because the setter will retain it. also [AT]property (nonatomic, retain) NSDate *date; is enough you dont need to declare anything else even [AT]synthesize is not necessary unless you want a specific var name instead of the default _date that will be generated for you. – Nicolas Manzini Aug 03 '13 at 08:20
  • Thank you, Nicolas Manzini. – Amit Farkash Aug 03 '13 at 08:30

1 Answers1

2

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

Mario
  • 4,530
  • 1
  • 21
  • 32
  • Thank you for your answer. Out of curiosity, why shouldn't I use setters in init ? For instant, if I'd like to set a string to something like str_ = @"something" it would be be easier than to have to retain it ? – Amit Farkash Aug 03 '13 at 08:35
  • It is a convention, though most of the time it might not cause harm. See this answer and search on SO - there are many answers to that question: http://stackoverflow.com/questions/11856672/objc-using-self-in-init-and-or-initwithframe/11856820#11856820 or http://stackoverflow.com/questions/192721/why-shouldnt-i-use-objective-c-2-0-accessors-in-init-dealloc – Mario Aug 03 '13 at 09:02
  • Also consider switching to ARC with any new projects. It is good to know about manual reference counting of course, but ARC makes a lot easier – Mario Aug 03 '13 at 09:12
  • Thanks. I'm working with Cocos2D and it's not using ARC yet, (as far as I last checked). – Amit Farkash Aug 04 '13 at 07:34