1

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 when 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.
}

}

2 Answers 2

4

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];
    }

}
Sign up to request clarification or add additional context in comments.

2 Comments

Should not the autorelease pool check the references to the object? 'date' is a class level variable, and can be used by other methods/functions in the class. Not it?
An object does not know what other objects have references to it, and the autorelease pool has no way of finding this out either. All it does when it's drained is blindly decrement the reference count of each object it's holding. If that objects reference count reaches zero it is then deallocated, irrespective of whether other objects still have references to it.
2

[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];
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.