Question about reference count of this code
In the code below, argume开发者_C百科nts has a reference count of 3 (shown by NSLog)...i would like to understand why...I am trying to manage the memory here and am running into some fundamental misunderstandings...it seems like every time the object is reference in the code the reference count goes up, however, in this case, arguments is only referenced once (other than the allocation), and would therefore lead me to believe that the reference count should only be 2. At any rate...can someone please explain to me why arguments has a retainCount of 3?
NSString *authToken = [[NSDictionary dictionaryWithContentsOfFile:[GetFilePath pathForFile]] objectForKey: @"auth_token"];
NSString *apiSig = [MD5Gen returnMD5Hash:[NSString stringWithFormat:@"xxxxxxx%@", authToken]];
NSString *arguments = [[NSString alloc] initWithFormat:@"xxxxxxxx%@%@", authToken, apiSig];
NSString *encodedArguments = [arguments stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding];
NSURL *url = [[NSURL alloc] initWithString: encodedArguments];
NSLog(@"%i", [arguments retainCount]);
(Since Dave asked for it)
Do not use -retainCount.
The absolute retain count of an object is meaningless.
You should call release
exactly same number of times that you caused the object to be retained. No less (unless you like leaks) and, certainly, no more (unless you like crashes).
See the Memory Management Guidelines for full details.
In this specific case, the retain count might be being bumped by stringByAddingPercentEscapesUsingEncoding:
as in internal implementation detail.
Beyond an intellectual curiosity, it really doesn't matter. If you retain an object, you should release it.
retainCount
is pretty useless since its gives back a meaningless number and should almost never be used for debugging purposes. In my opinion, it should just be deprecated :-)
You shouldn't really ever use retainCount
- the number one reason for this is that a lot of methods return retained+autoreleased objects, which means that their retainCount
will be one higher every time you retrieve the object (until the autorelease pool is drained).
It's of no use for you, and it probably shouldn't be a public method on NSObject
, since it serves no use or function (outside of Apple's private Foundation code) except to confuse beginners who are trying to learn Cocoa/Objective-C.
To get your head around memory management in Obj-C, go read Apple's memory management guide: http://developer.apple.com/library/ios/#documentation/Cocoa/Conceptual/MemoryMgmt/MemoryMgmt.html
精彩评论