• Open Menu Close Menu
  • Apple
  • Shopping Bag
  • Apple
  • Mac
  • iPad
  • iPhone
  • Watch
  • TV
  • Music
  • Support
  • Search apple.com
  • Shopping Bag

Lists

Open Menu Close Menu
  • Terms and Conditions
  • Lists hosted on this site
  • Email the Postmaster
  • Tips for posting to public mailing lists
Retain counts with a dictionary
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Retain counts with a dictionary


  • Subject: Retain counts with a dictionary
  • From: Jeffrey Mattox <email@hidden>
  • Date: Sat, 15 Mar 2003 19:25:02 -0600

I am using an NSMutableDictionary as an associative array (a la, a Perl hash, I'm in heaven :-).

I add keys (which are strings) to the dictionary. If the key already exists, nothing happens; if the key does not exist, it gets added. Since I'm only interested in the existence or not of theKey (in later code, not shown), I have no need for the object, but it cannot be nil, so I use @"". All this seems to work.

char *myCString;
NSString *thekey;
while (...) {
...
myCString = .... // varies
theKey = [[NSString alloc] initWithCString:myCString];
[theDictionary setObject:@"" forKey:theKey];
[theKey release];
}

The documentation for NSMutableDictionary says:

if theKey is new: the object is retained, but the key is copied
if theKey exists: the previous object is released and
the new object is retained

1. What I am seeing, however, is that if theKey is new, it's retain count after being copied becomes 2. (If theKey is not new, it's retain count stays at 1.) Why is the key's retain count incremented if the key is just copied?

I realize that I could use theKey = [NSString stringWithCString:mCString] and then not release it in the loop, but that's a discussion I started in another thread. Either way, I need to understand how the retain count works and using alloc/init gives me better control.

2. Is it okay to use @"" for the objects in the loop? Will that create a new null string for each addition, or reuse the same one? Is there a better way?

Jeff
_______________________________________________
cocoa-dev mailing list | email@hidden
Help/Unsubscribe/Archives: http://www.lists.apple.com/mailman/listinfo/cocoa-dev
Do not post admin requests to the list. They will be ignored.

  • Follow-Ups:
    • Re: Retain counts with a dictionary
      • From: Sherm Pendley <email@hidden>
    • Re: Retain counts with a dictionary
      • From: Greg Titus <email@hidden>
    • Re: Retain counts with a dictionary
      • From: Nicholas Riley <email@hidden>
  • Prev by Date: Re: NSMutableArray/NSArray and lossyCString
  • Next by Date: Confused between NSCoder and NSArchiver
  • Previous by thread: Re: Trouble with a save panel
  • Next by thread: Re: Retain counts with a dictionary
  • Index(es):
    • Date
    • Thread