Objective C instance variable initialization in a method
Did any body get this issue? If I need an instance variable, not as a property, and initialize this variable in a method, then when I need it, it is already released. It happens for autoreleased objects. What is the reason for this?
Usually instance variable should have the whole lifetime of the class object. But it seems if the variable is local to a function, and its a autorelease object, it is released wh开发者_开发问答en the function exits.
MyClass.h
@interface MyClass:UIViewController {
NSDate * date;
}
MyClass.m
@implementation MyClass {
- (void) anInit {
date = [NSDate date];
}
- (void) useDate {
NSLog (@"%@", date);
// here date is already release, and get bad access.
}
}
You need to retain
date.
An autoreleased object will be released when the autorelease pool is next drained. When this happens has nothing to do with the lifecycle of your object.
Your implementation should look like this:
@implementation MyClass {
- (void) anInit {
date = [[NSDate date] retain]; // or [[NSDate alloc] init]
}
- (void) useDate {
NSLog (@"%@", date);
}
- (void) dealloc {
[date release];
[super dealloc];
}
}
[NSDate date]
is a Convenience Constructor and is autoreleased, you need to add a retain call. Also make sure anInit is only called once or you will create a memory leak without calling [date release]
first.
- (void) anInit {
date = [[NSDate date] retain];
}
精彩评论