Creating a new NSString instance has a value of 3

I am trying to copy a string that is passed to a method like this:

-(void) parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName attributes:(NSDictionary *)attributeDict { NSLog( @"elementName, %@: %i", elementName, [elementName retainCount] ); // rc = 2 if ( currenttag ) [currenttag release]; NSLog( @"currenttag: %i", [currenttag retainCount] ); // rc = 0 //currenttag = [[NSString alloc] initWithString:elementName]; // track current element [self setCurrenttag:elementName]; NSLog( @"currenttag: %i", [currenttag retainCount] ); // rc = 3 . . . } 

setCurrenttag - synthesized accessor ( @property (copy) ). I realized that this would create a completely new object instead of just referencing elementName . The above behavior behaves as if it maintains a reference to elementName and causes persistence. The commented code bit shows the same behavior.

These methods implement the NSXMLParserDelegate protocol, but I need to track specific element names (but not all).

Is there anything I am missing regarding NSString objects and memory management on iphone.

Also, as a link, I run this on an iPhone simulator with Xcode 3.6.

+2
source share
6 answers

For immutable Foundation classes, such as NSString, copy simply saves the object. Duplication of an object that is known to be immutable will be a waste of resources, so this does not happen. This is stated in the documentation for the NSCopying protocol. One of the options for implementing the protocol:

  • Implement NSCopying by saving the original instead of creating a new copy when the class and its contents are immutable

In the general case, if you know that instances of one of your classes will be immutable, it is completely correct in order to save the target object and not duplicate it.

+5
source

Do not rely on retainCount to be intuitive. It probably happens that the line in question is not changed, so the β€œcopy” ends up just holding the existing line (this is great, because it can never change).

+2
source

Whenever you deal with objects, you should never directly access the conservation account, you should only deal with them in terms of differences. All you need to know is to save +1 and release -1

+1
source

Just a guess, but since NSString is immutable, there may be an optimization that the property does retain instead of creating a new object.

0
source

Do not trust keepCount. Just release every object for which you named alloc, copy, retain, and new.

0
source

In my experience, saveCount does not always return the actual number of accumulations, and this can be tricky. NSString is an immutable object, so it can behave differently than other objects, I'm not sure that Objective-C implements a string pool, like java, since it is not mentioned in the documentation.

0
source

All Articles