A method returns an nsstring object, calls the method in the event, and tries to return the nsstring object of the release method.
-(Nsstring *) createnewstring {// scenario 1 return [[[nsstring alloc] initwithformat: @ "% @", @ "1223344"] autorelease]; // case 2 return [[[nsstring alloc] initwithstring: @ "1223344"] autorelease]; // case 3 return @ "1223344" ;}// call the method, in the event-(ibaction) Touchdown :( ID) sender {nsstring * STR = [self createnewstring]; nslog (@ "output 1, Count: % d ", [STR retaincount]); [STR release]; nslog (@ "Output 2, Count: % d", [STR retaincount]);}
Case 1:
21:33:38. 817 autorelease [718: b303] Output 1 count: 1
21:33:38. 819 autorelease [718: b303] ***-[cfstring retaincount]: Message sent to deallocated instance 0x4e5060
At this time, the xcode breakpoint is stuck in output 2... I thought it was output 2, and the error was thrown as follows:The retaincount method cannot be executed for a recycled object.. (Whether there is a difference between recycling and nil)
Comment output 2
Result:
21:35:02. 690 autorelease [745: b303] Output 1 count: 1
21:35:02. 692 autorelease [745: b303] ***-[cfstring release]: Message sent to deallocated instance 0x6895940
The breakpoint has already run to the main method. At this time, it is determined to be [STR release]. The method throws an error. It is understood that the release operation cannot be performed manually on an autorelease object.
Modify the call method:
-(Ibaction) Touchdown :(ID) Sender {
Nsstring*Str=[[Self createnewstring]Retain];
Nslog (@"Output 1 count: % d", [STR retaincount]);
[STR release];
Nslog (@"Output 2 count: % d", [STR retaincount]);
}
In this case, the method is successfully executed, and no exception occurs. The output is:
21:40:42. 029 autorelease [804: b303] Output 1 count: 2
21:40:42. 030 autorelease [804: b303] Output 2 count: 1
It is understood that when you need to operate an object that is autorelisted. you can retain him first, and then release him when he is not needed. (This is the issue of object ownership ).. retain = counter + 1
--------------------------------------------------------------------------------------------------------------------------------------------
Case 2, Case 3: methods before and after modificationCodeCan run in the past.
The output values are:
21:49:16. 993 autorelease [864: b303] Output 1 count: 2147483647
21:49:16. 995 autorelease [864: b303] Output 2 count: 2147483647
It is understood as: initwithstring: @ "1223344". A constant string is created and is limited to release and retain objects by the system. It is somewhat similar to the singleton mode recommended by Apple.
Note: 2147483647 is the value of uint_max.
If return [[[nsstring alloc] init] stringbyappendingstring: @ "Hello world! "];
Will there be Memory leakage in this ??? Continue to study ....
Http://stackoverflow.com/questions/1390334/nsstring-retain-count for Reference