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?
In order to access the variable as a property, you need to invoke it as
Otherwise, it is just doing a straight assign to the variable storing it behind. When you declare a property as
retainwithin the automatically generatedsetMyDatefunction that is invoked when you useself.myDate = someDate;a call toretainon 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.myDatemethod to ensure proper use of reference counting functions