Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective-C memory issue (iPhone)

I'm somewhat confused by the following behavior I'm seeing within an Xcode project compiled for the iPhone simulator (or device):

NSString *test = [[NSString alloc] initWithCString:"foo"];

NSLog(@"test retain count = %d", [test retainCount]); // prints 1

[test release];

NSLog(@"test retain count = %d", [test retainCount]); // also prints 1 instead of 0

However, any further attempts to access 'test' result in a crash of the Xcode enviroinment, whether it be another [test retainCount] NSLog statement or otherwise (even if only to check if test is equal to nil).

Thoughts? Compiled within a simple View based test project...code exists within project's applicationDidFinishLaunching method.

Clarification -- I know NOT to do the above in practice. This was just a test to see why in some debugging cases a retain count of 1 wasn't actually reflecting the real state of an object. Thanks for your responses. This was just a test stub to see why I was seeing certain behavior in a few cases. What I'm really trying to do is track down a very small memory leak (0.06MB) that is consistently being created whenever I destroy/recreate a custom view.

like image 493
Ari Braginsky Avatar asked Jul 16 '26 00:07

Ari Braginsky


2 Answers

Retain counts are a debugging aid and can be misleading based on what Cocoa may be doing behind the scenes. This is particularly true with string literals where the data is permanently available and is never really deleted.

Concentrate of ensuring your code follows the Cocoa memory management rules with respect to object ownership. Where necessary, use Instruments to check for actual memory leaks.

like image 116
Andrew Grant Avatar answered Jul 18 '26 14:07

Andrew Grant


You are calling retainCount on test after it has been released and possibly deallocated, so definitely the result is not reliable, not to mention you shouldn't be sending dealloced objects any messages.

like image 30
codelogic Avatar answered Jul 18 '26 13:07

codelogic



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!