Note that there are some explanatory texts on larger screens.

plurals
  1. POWhy does this cause memory leaks?
    primarykey
    data
    text
    <p>I'm new to Objective-C, and I've read some memory management articles but am having trouble.</p> <p>I hava a class something like this:</p> <pre><code>-(UIWebView*)getWebView{ //UIWebView* webview = [UIWebView initWithFrame:self.frame]; edited,the original wrong line UIWebView* webview = [[UIWebView alloc] initWithFrame:self.frame]; return webview; } -(void)addToSelf{ UIWebView* view = [self getWebView]; [self addSubview:view]; [view release]; //release here } </code></pre> <p>In my thought, objc objects are all like C pointers (it is ?) And thinking like this:</p> <pre><code>UIWebView* webview = [[UIWebView alloc] initWithFrame:self.frame]; //retain +1 UIWebView* view = [self getWebView]; //just a pointer to the same object ? [self addSubview:view]; //retain +1 [view release]; //retain -1 </code></pre> <p>Now view's <code>retainCount = 1</code>. Then this viewController will handle the webview's life cycle.</p> <p>There must be something wrong with my thought (sure also the code), <strong>but I don't know why</strong> .</p> <pre><code>UIWebView* webview = [[[UIWebView alloc] initWithFrame:self.frame] autorelease]; </code></pre> <p>When I remove the last release line, code works fine, why? <strong>What's the difference?</strong></p> <p>--------------edit line---------------</p> <p>Few minutes ago , there's an answer about it but it's disappeared , now I rewrite my thought:</p> <p>The answer says: </p> <p>When returning object from method , i must use <strong>autorelease</strong> to tell compiler I have end with it, and then using addSubview , finish (no need releasing).</p> <p>I know this is right , but why it's right ?</p> <p>In most of codes:</p> <pre><code>-(void)someMethod{ UIWebView* webview = [[UIWebView alloc] initWithFrame:self.frame]; [self addSubview:webview]; [webview release]; } </code></pre> <p>this works fine, but when separate the code to two methods like the top ,it's not.</p> <p>Why i must use <strong>autorelease</strong> when returning object? </p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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