假设我有这样一个成员:
@property (retain, nonatomic) Student *student;
@synthesize student;现在假设在其他班级中,我正在设置学生,意味着我将一些新创建的对象分配给学生。现在假设学生之前已经引用了一个对象,所以我的问题是,当我将新的对象ref赋给student时,这个对象会被释放吗?在这段代码中
someClassObjectRef.student = newStudent; //someClassObjectRef.student is already having one student object ref那么,在赋值新对象之前,我是否必须显式释放旧对象,还是@synthesize会在后面这样做呢?我希望你能理解我想说的话。
注意:不使用ARC。
谢谢。
发布于 2012-07-27 17:05:08
在保留新的对象之前,合成的setter将release任何以前保留的对象;类似于:
- (void)setStudent:(Student *)student
{
[student retain];
[_student release];
_student = student;
}请注意,它在 release-ing旧对象之前先释放传入的对象;这允许您将相同的对象传递到它本身,而不需要释放它。
还有其他方法可以做到这一点,例如:
- (void)setStudent:(Student *)student
{
if (student != _student)
{
[_student release];
_student = [student retain];
}
}释放学生对象的正确方法是在dealloc方法中设置nil:
- (void)dealloc
{
[self setStudent:nil]; // or self.student = nil;
[super dealloc];
}发布于 2012-07-27 17:21:20
我希望你想在- (void)dealloc或`- (void)viewDidUnload上进行内存管理
- (void)dealloc {
[student release]; or [self setStudent:nil];
[super dealloc];
}这些是内存管理的最佳实践,或者您可以在使用时创建对象,并在使用后将其释放。
Student *student = [[Student alloc]init];
// Do Some Work over here
[student release];https://stackoverflow.com/questions/11684665
复制相似问题