這段代碼有什么問題,如何修改?
for (int i = 0; i < someLargeNumber; i++) {
NSString *string = @”Abc”;
string = [string lowercaseString];
string = [string stringByAppendingString:@"xyz"];
NSLog(@“%@”, string);
}
這里,我們暫定someLargeNumber = 10W.
這段代碼在ARC中是沒有問題的,在MRC中,才有問題.問題也很顯然,創(chuàng)建的字符串對象并沒有釋放.
字符串對象是比較特殊的對象,release,或者autorelease并不能有效釋放掉.在模擬器上重復(fù)10w次可以發(fā)現(xiàn)內(nèi)存從21.6MB一直增長到40MB.
原始代碼循環(huán)執(zhí)行前
原始代碼循環(huán)執(zhí)行后
可見,沒有釋放掉.
正確的修改方案如下:
for(int i = 0; i<100000;i++){
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
NSString *string = @"Abc";
string = [string lowercaseString];
string = [string stringByAppendingString:@"xyz"];
NSLog(@"%@",string);
[pool drain];
}
修改代碼執(zhí)行循環(huán)后
可見,對于MRC下字符串的正確釋放,用NSAutoreleasePool是一個解決方案.