I’m new to Objective-C, and I’ve read some memory management articles but am having trouble.
I hava a class something like this:
-(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
}
In my thought, objc objects are all like C pointers (it is ?)
And thinking like this:
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
Now view’s retainCount = 1.
Then this viewController will handle the webview’s life cycle.
There must be something wrong with my thought (sure also the code),
but I don’t know why .
UIWebView* webview = [[[UIWebView alloc] initWithFrame:self.frame] autorelease];
When I remove the last release line, code works fine, why?
What’s the difference?
————–edit line—————
Few minutes ago , there’s an answer about it but it’s disappeared , now I rewrite my thought:
The answer says:
When returning object from method , i must use autorelease to tell compiler I have end with it, and then using addSubview , finish (no need releasing).
I know this is right , but why it’s right ?
In most of codes:
-(void)someMethod{
UIWebView* webview = [[UIWebView alloc] initWithFrame:self.frame];
[self addSubview:webview];
[webview release];
}
this works fine, but when separate the code to two methods like the top ,it’s not.
Why i must use autorelease when returning object?
It looks as if you don’t alloc the UIWebView:
That means you probably don’t have a valid UIWebView, and a retain count that is undefined, since the code for UIWebView is actually using some unknown piece of memory. If this works, you are lucky.