问题描述
我有以下代码:
NSString * tempString = [[NSString alloc] initWithFormat:@%d/%d/%d",day,month,year];
NSString *tempString = [[NSString alloc] initWithFormat:@"%d/%d/%d",day, month, year];
dateString = tempString;
dateString = tempString;
[tempString版本];
[tempString release];
NSLog(@"datstring和tempstring的保留计数为%d和%d",[dateString keepCount],[tempString keepCount]);
NSLog(@"retain count for datstring and tempstring is %d and %d",[dateString retainCount],[tempString retainCount]);
NSLog(@%@和%@",dateString,tempString)
NSLog(@"%@ and %@",dateString, tempString)
现在,即使我在之前的行中将其释放,它也会将tempString的保留计数打印为1(dateString保留计数= 1).同样,显示两个字符串的NSlog语句不显示任何内容.我认为这是因为,根据我的代码,dateString指向tempString的位置,而tempString已被释放,因此NSlog将无法打印该字符串.但是,为什么tempString的保留计数= 1?
Now it prints the retain count of tempString as 1 (also dateString retain count = 1) even though I am releasing it in the line before. Also the NSlog statement printing the two strings doesn't display anything. Im assuming this is because, since by my code, dateString is pointing to the location of tempString and tempString has been released, NSlog will be unable to print the string. But then why is the retain count of tempString = 1?
如果我替换行
dateString = tempString;
dateString = tempString;
与
dateString = [NSString stringWithString:tempString];
dateString = [NSString stringWithString: tempString];
然后,NSlog语句同时输出dateString和tempString的值,并将其保留计数显示为1.当我在上一行中释放tempString的值时,该如何打印?
then the NSlog statement prints the values of both dateString and tempString and displays their retain counts as 1. How is the value of tempString getting printed when i am releasing it in the previous line?
推荐答案
阅读iphone文档:
Read the iphone documentation:
如jamapag所述,release
只是告诉运行时运行dealloc
,这意味着该内存被标记为可重用,而不是已被清除.对于retainCount
为1的对象,运行时通常不会在dealloc
之后递减retainCount
值.
As jamapag states release
simply tells the runtime to run dealloc
meaning that the memory is marked as reusable not that it has been cleared. For objects with a retainCount
of 1, the runtime usually doesnt decrement the retainCount
value after the dealloc
.
要注意的另一件事是,您不应该像使用retainCount
一样向已发布的对象发送消息,否则您肯定会得到一些意外的行为
Another thing to note is that you should not send messages to released objects as you are doing with retainCount
you are bound to get some unexpected behaviours
这篇关于有关NSString对象和内存管理的查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!