I got this code off another thread on here and it works perfectly, but it leaks, and I don’t know how to release it. I have tried adding “autorelease” statements to the GoToNext alloc line. It didnt help. Anyone know how to properly handle this?
webView.delegate = [[GoToNext alloc] initWithTarget:self andNext:@selector(loadUpdateGraph)]; //leak
This is the GoToNext code:
.h
@interface GoToNext : NSObject <UIWebViewDelegate> {
id __weak target;
SEL next;
}
-(id)initWithTarget:(id)target andNext:(SEL)next;
-(void)webViewDidFinishLoad:(UIWebView *)webView;
@end
.m
#import "GoToNext.h"
@implementation GoToNext
-(id)initWithTarget:(id)_target andNext:(SEL)_next {
self = [super init];
if (self) {
target = _target;
next = _next;
}
return self;
}
-(void)webViewDidFinishLoad:(UIWebView *)webView {
[target performSelector:next];
}
@end
When you create an instance of
GoToNextusingalloc, that instance has a retain count of 1. Somewhere in your app you must release this instance before you lose your only reference to it (which in this case is thedelegateproperty ofwebView). Thedelegateproperty of aUIWebViewusesassignsemantics, so assigning your instance ofGoToNextto that property does not retain it. This means that you cannotreleaseorautoreleaseit while it is still the delegate ofwebVieworwebView.delegatewill point to deallocated memory.If you’re sure you’re only setting
webView.delegateonce in the lifecycle of the class containing this code, you can get by with just put[webView.delegate release]in thedeallocmethod of that class. If you’re setting it more than once, you might try creating a method like:And using that method to set
webView‘s delegate. There are other ways to handle this situation, but I think this method will probably require the fewest changes to your code.Of course, in my opinion the best solution of all is to just convert the application to ARC and never have to worry about this kind of thing again.