Mutablecopy mem泄露

这行出现了内存泄露?为什么?

Person.h
-------
NSMutableString *address;

Person.m
--------
@synthesize address;

-(id) init
{
    self = [super init];
    address = [[NSMutableString alloc] init];

    return self;
}

-(void) funcA()
{
    [address appendFormat:@"located|at|%@", @"Singapore"];
     address = [[address stringByReplacingOccurrencesOfString:@"|" withString:@" "] mutableCopy];
}

-(void) dealloc
{
    [address release];
    [super release]
}

=address是一个NSMutableString,也是一个property。我只在dealloc方法中进行释放。

这段代码中存在内存泄露。在funcA方法中,你创建了一个新的NSMutableString对象并将它赋值给address属性,但没有释放原来的address对象。因此在dealloc方法中释放address对象时,只能释放最后一次赋值的对象,而之前创建的对象就成了野指针,无法释放,导致内存泄露。


可以在funcA()中使用setString: 方法替换而不是使用 assignment 运算符来避免这种情况。