2011-05-19 88 views
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]; 
} 

回答

0

這樣做很不錯。這個想法很基本。您不希望委託人在關閉屏幕時收到任何委派信息。所以設置代理-viewWillAppear:-viewWillDisappear:的想法是正確的。但是我沒有看到代碼中正在實現的委託方法。

+0

但委託也被設置在-viewDidLoad?我沒有包含我正在使用的UIWebView委託方法(webViewDidStartLoad,webViewDidFinishLoad,didFailLoadWithError),只是爲了避免帖子冗長。 – 2011-05-19 12:18:25

+0

是的,你是對的。您可以安全地移除'-viewDidLoad'中的委託分配。但是,它不會影響對象的保留計數,因爲委託被定義爲「assign」屬性。 – 2011-05-19 13:08:46

+0

因爲我們聲稱擁有兩次,所以webview被釋放兩次(autorelease + release)。一旦實例化對象並設置「webView」屬性一次。我們只在'-viewDidLoad'中放棄所有權,並保留對該對象的引用。這樣我們就可以確保對象在我們需要的時間內停留。 – 2011-05-19 13:11:09