0

我有一个关于使用 NSString 的内存管理问题。看下面的简单代码:

NSString *catSeq = [[NSString alloc] init];

for (NSString *cat in cats) {
    catSeq = [catSeq stringByAppendingFormat:cat];
    catSeq = [catSeq stringByAppendingFormat:@"  "];
}

catLabel.text = catSeq;

[catSeq release];   

// This code expresses what all I want to do, but Memory leak happened
// below I delete lines of code to find out the reason

-----------------------------------------------------

NSString *catSeq = [NSString string];

for (NSString *cat in cats) {
    catSeq = [catSeq stringByAppendingFormat:cat];
    catSeq = [catSeq stringByAppendingFormat:@"  "];
}

catLabel.text = catSeq; 

// Memory leak not happened  
-----------------------------------------------------

NSString *catSeq = [[NSString alloc] init];

catLabel.text = catSeq; 

[catSeq release];   

// Memory leak not happened
4

3 回答 3

1

试试这种方式,自动释放。

 NSString *catSeq = [[[NSString alloc] init]autorelease];

for (NSString *cat in cats) {
    catSeq = [catSeq stringByAppendingString:cat];
    catSeq = [catSeq stringByAppendingString:@"  "];
}

catLabel.text = catSeq;
于 2012-06-04T07:38:38.713 回答
1

将您的代码更改为:

NSString *catSeq = @"";

for (NSString *cat in 猫) {

catSeq = [catSeq stringByAppendingFormat:cat];
catSeq = [catSeq stringByAppendingFormat:@"  "];

}

catLabel.text = catSeq;

于 2012-06-04T10:50:24.660 回答
0

使用其中一种方法

 catSeq = [catSeq stringByAppendingFormat:@"%@",cat];
    catSeq = [catSeq stringByAppendingFormat:@"%@",@"  "];

或者

 catSeq = [catSeq stringByAppendingString:cat];
    catSeq = [catSeq stringByAppendingString:@"  "];
于 2012-06-04T07:37:54.697 回答