Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Note also that this line of code:</p> <pre><code>[name setText:[[NSString alloc] initWithCString:myCPlusPlusObject-&gt;cppname.c_str()]]; </code></pre> <p>leaks the created string.</p> <p>Go back and read the memory management rules at <a href="http://developer.apple.com/documentation/Cocoa/Conceptual/MemoryMgmt/Articles/mmRules.html" rel="nofollow noreferrer">http://developer.apple.com/documentation/Cocoa/Conceptual/MemoryMgmt/Articles/mmRules.html</a>.</p> <p>The main issue is there you have allocated the string, therefore you have taken ownership of it, and you then never release it. You should do one of the following:</p> <pre><code>[name setText:[[[NSString alloc] initWithCString:myCPlusPlusObject-&gt;cppname.c_str() encoding:NSUTF8StringEncoding] autorelease]]; </code></pre> <p>or</p> <pre><code>NSString* myCPlusPlusString = [[NSString alloc] initWithCString:myCPlusPlusObject-&gt;cppname.c_str() encoding:NSUTF8StringEncoding]; [name setText:myCPlusPlusString]; [myCPlusPlusString release]; </code></pre> <p>or</p> <pre><code>[name setText:[NSString stringWithCString:myCPlusPlusObject-&gt;cppname.c_str() encoding:NSUTF8StringEncoding]]; </code></pre> <p>The latter is the best as far as code simplicity is concerned. The middle one is the best as far as memory usage is concerned, which is frequently an issue on the iPhone.</p> <p>The first one is likely identical to the last one - I say "likely" because there is no guarentee that stringWithCString returns an autoreleased object. It probably does, but whether it does or not is not your concern, all that matters to you is that you do not take ownership of the string because the method name does not begin with “alloc” or “new” or contains “copy” and so you are not responsible for releaing it.</p>
 

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