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 *猫の猫) {

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 に答える