Note that there are some explanatory texts on larger screens.

plurals
  1. PO@property copy & manual memory management with an autorelease pool
    text
    copied!<p>I have a class that copy's an NSString and print's it's retain count and address.</p> <pre><code>@interface TestStringPointer : NSObject @property (copy) NSString *stringTest; - (void)printPointer; @end @implementation TestStringPointer - (void)printPointer { NSLog(@"PrintPointer:%p\n RetainCount:%lu", _stringTest, [_stringTest retainCount]); } @end </code></pre> <p>In my main function I was doing a bit of investigation on the String's pointer and ran into an issue.</p> <pre><code>int main(int argc, const char * argv[]) { NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; TestStringPointer *test = [[TestStringPointer alloc] init]; NSString *myString = [NSString stringWithUTF8String:"Hello World"]; NSLog(@"MyString: %p \n RetainCount:%lu", myString, [myString retainCount]); [test setStringTest:myString]; [test printPointer]; [myString release]; [pool drain]; while (1) { [test printPointer]; } return 0; } </code></pre> <p>When I debug the app it crashes the 3rd time through the while loop (the number of times through the loop varies). I understand that the copy doesn't occur cause the string isn't mutable. After it's released in main, I would've expected it to go back to 1. <br> 1) If an object isn't autoreleased, is it still affected the autorelease pool?<br> 2) Wouldn't having a max retain count prevent the object from being drained in the pool, or does that flag it for deletion?<br> 3) Shouldn't the copy have stepped in at some point and actually made a copy before it was deleted?</p> <blockquote> <p>StringPointerTest[2253:303] MyString: 0x100100f60 RetainCount:1<br> StringPointerTest[2253:303] PrintPointer:0x100100f60 RetainCount:2<br> StringPointerTest[2253:303] PrintPointer:0x100100f60 RetainCount:1152921504606846975<br> StringPointerTest[2253:303] PrintPointer:0x100100f60 RetainCount:1152921504606846975<br></p> </blockquote> <p>If I modify main and remove the pool<br></p> <pre><code>int main(int argc, const char * argv[]) { TestStringPointer *test = [[TestStringPointer alloc] init]; NSString *myString = [NSString stringWithUTF8String:"Hello World"]; NSLog(@"MyString: %p \n RetainCount:%lu", myString, [myString retainCount]); [test setStringTest:myString]; [test printPointer]; [myString release]; while (1) { [test printPointer]; } return 0; } </code></pre> <p>All is right... Forever...</p> <blockquote> <p>StringPointerTest[423:303] MyString: 0x10010a670 RetainCount:1 <br> StringPointerTest[423:303] PrintPointer:0x10010a670 RetainCount:2 <br> StringPointerTest[423:303] PrintPointer:0x10010a670 RetainCount:1 <br> ...</p> </blockquote>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload