1

i want initialize a nsdate with a specific date, to use it in all my code an i'm doing this:

.h

@property (nonatomic, retain) NSDate *myDate;

.m

@synthesize myDate;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        [formatter setDateFormat:@"yyyy-MM-dd"];

        myDate = [formatter dateFromString:@"2050-01-01"];
    } 
    return self;
}

then in the code, if i read that nsdate like in this way:

NSLog(@"%@",myDate);

or if i use isEqualToDate, give me a exc_bad_access

why?

Dan F
  • 16,994
  • 5
  • 69
  • 108
Piero
  • 8,533
  • 18
  • 82
  • 153
  • Note the perils of using accessors in `init...` methods: http://stackoverflow.com/questions/192721/why-shouldnt-i-use-objective-c-2-0-accessors-in-init-dealloc – petert May 29 '12 at 13:19

1 Answers1

3

In order to access the variable as a property, you need to invoke it as

self.myDate = [formatter dateFromString:"2050-01-01"];

Otherwise, it is just doing a straight assign to the variable storing it behind. When you declare a property as retain within the automatically generated setMyDate function that is invoked when you use self.myDate = someDate; a call to retain on the object passed in is made in order to hold onto the object.

In general, it is considered a best practice to only access your properties through the automatically generated methods, or through self.myDate method to ensure proper use of reference counting functions

Dan F
  • 16,994
  • 5
  • 69
  • 108
  • Instead of using self.myDate, synthesizes properties can automatically create an ivar. @synthesize myDate = _myDate; and then use _myDate = [formatter dateFromString:...]; – bbarnhart May 29 '12 at 13:25
  • He would still need to call `retain` on the object returned from `dateFromString` or it will be autoreleased at the end of the init function – Dan F May 29 '12 at 13:26