Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSString length and retainCount. Clarification needed

Based on the following code, please advise

NSString *str= [[NSString alloc] initWithString:@"Hello world"];   

NSLog(@"Length: %lu\n", [str length]);              // 11
NSLog(@"Retain count is %lu\n", [str retainCount]); //1152921504606846975

[str release];

NSLog(@"%lu\n", [str length]);                      // 11
NSLog(@"Retain count is %lu\n", [str retainCount]); //1152921504606846975
  1. Originally I was wondering why the number was so large but then saw a a post explaining it. Let me ask this instead ... Why does this number change greatly whether i use %d vs %lu. Originally, i used %d, but got a warning saying that "Conversion specified type int but the argument has the type NSUInteger (aka unsigned long). A fix was to change %d to %lu"

  2. Why doesn't the retain count decrement? Large number still shows up unchanged, after the str is sent release

  3. Why am i still able to access the str, after it was sent release?

like image 914
James Raitsev Avatar asked Feb 23 '23 13:02

James Raitsev


1 Answers

This may be a hard answer to accept, but it's what you should do:

  1. Don't worry about it. (in terms of %d/%lu, those specifiers simply expect different data types, and %d (int) has a much smaller and different range from %lu (unsigned long))
  2. Don't worry about it.
  3. Don't do it, and especially don't rely on it.

It may be because you started with a constant string (@"Hello world") that the memory isn't being deallocated when you call release, and the retainCount is large. But if you have to care about the retainCount, you're doing it wrong.

You are releasing the string in the right place, and that's what matters — don't ever try to use it later.

like image 163
jtbandes Avatar answered Mar 07 '23 19:03

jtbandes