0
我已经使用我发现的UIWebView实现了示例代码,但它看起来并不正确,尽管它有效。特别是因为它设置了两次UIWevView委托(在viewDidLoad和viewWillAppear中)。另外,myWebView被设置为autorelease对象,但随后它会以dealoc的形式发布。我希望有人能告诉我如何清理这件事。UIWebView委托代码看起来不对
// *** WebViewController.h ***
@interface WebViewController : UIViewController
<UIWebViewDelegate>
{
UIWebView *myWebView;
UIActivityIndicatorView *activityIndicator;
}
@property (nonatomic, retain) UIWebView *myWebView;
@property (nonatomic, retain) UIActivityIndicatorView *activityIndicator;
@end
// *** WebViewController.m ***
@synthesize myWebView;
- (void) viewDidLoad {
[super viewDidLoad];
// - - - - -> Create the UIWebView
CGRect webFrame = [[UIScreen mainScreen] applicationFrame];
webFrame.origin.y += 42.0;
webFrame.size.height -= 106.0;
self.myWebView = [[[UIWebView alloc] initWithFrame:webFrame] autorelease];
self.myWebView.backgroundColor = [UIColor whiteColor];
self.myWebView.scalesPageToFit = YES;
self.myWebView.autoresizingMask = (UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
self.myWebView.delegate = self;
[self.view addSubview: self.myWebView];
// - - - - -> Create the UIActivityIndicatorView
self.activityIndicator = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite] autorelease];
[self.view addSubview: self.activityIndicator];
self.activityIndicator.center = CGPointMake(135,438);
[self.myWebView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.someURL.com/"]]];
- (void) viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
self.myWebView.delegate = self;
}
- (void) viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
[self.myWebView stopLoading];
self.myWebView.delegate = nil;
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}
- (void) dealloc {
myWebView.delegate = nil;
[myWebView release];
[activityIndicator release];
[super dealloc];
}
但委托也被设置在-viewDidLoad?我没有包含我正在使用的UIWebView委托方法(webViewDidStartLoad,webViewDidFinishLoad,didFailLoadWithError),只是为了避免帖子冗长。 – 2011-05-19 12:18:25
是的,你是对的。您可以安全地移除'-viewDidLoad'中的委托分配。但是,它不会影响对象的保留计数,因为委托被定义为“assign”属性。 – 2011-05-19 13:08:46
因为我们声称拥有两次,所以webview被释放两次(autorelease + release)。一旦实例化对象并设置“webView”属性一次。我们只在'-viewDidLoad'中放弃所有权,并保留对该对象的引用。这样我们就可以确保对象在我们需要的时间内停留。 – 2011-05-19 13:11:09