【问题标题】:retain viewcontroller - message sent to deallocated instance保留视图控制器 - 发送到已释放实例的消息
【发布时间】:2014-04-07 21:19:53
【问题描述】:

我正在尝试使用 UIWebViewDelegate,但是,当我将委托设置为它自己时,我收到“发送到已释放实例的消息”错误。

实际错误:“2014-04-07 22:12:05.402 AppName[746:60b] -[WebViewController respondsToSelector:]: message sent to deallocated instance 0xa47ae00"

我猜这是因为 WebViewController 实例没有被保留?

谁能指出我正确的方向?

我的结构是: RootViewController > WebViewController(委托)> WebView

// root.h
@interface RootViewController : UIViewController
@property (strong, nonatomic) WebViewController * webViewController;
@end

// root.m

#import "RootViewController.h"
#import <UIKit/UIKit.h>
#import "WebViewController.h"

@interface RootViewController ()

@end

@implementation RootViewController

- (void)viewDidLoad
{

    _webViewController = [[WebViewController alloc] init];

    [self.view addSubview:_webViewController.view];

}

@end

// .h

#import <UIKit/UIKit.h>

@interface WebViewController : UIViewController <UIWebViewDelegate>
@property(strong) UIWebView *webView;
@end

// .m

#import "WebViewController.h"

@interface WebViewController ()
@end

@implementation WebViewController

- (void)viewDidLoad
{
    _webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height)];
    _webView.delegate = self;
    NSString *url = @"http://google.com/";
    NSURL *nsurl = [NSURL URLWithString:url];
    NSURLRequest *nsrequest = [NSURLRequest requestWithURL:nsurl];
    [_webView loadRequest:nsrequest];
    [self.view addSubview:_webView];
}

-(void)webViewDidStartLoad:(UIWebView *)webView {
    NSLog(@"ui web view started load");
}

【问题讨论】:

  • webViewController 被 ivar 指针保留,因此似乎不是这样。我一目了然没有答案,但我确实有一条评论,那就是您忘记将 nonatomic 添加到 webView 属性。几乎可以肯定是无意的。
  • 您能否将详细信息粘贴到实际消息中,以防您没有描述某些内容?
  • @PhillipMills 添加了错误信息

标签: ios objective-c automatic-ref-counting


【解决方案1】:

尝试将您的代码从loadView 移到viewDidLoad,并删除您对loadView 的调用。我相信 loadView 在视图控制器被实例化并显示时会自动调用,因此再次调用它可能会导致您实例化您的 webview 两次。

来自文档:

你不应该直接调用这个方法。视图控制器调用 此方法在请求其视图属性但当前为 nil 时。 此方法加载或创建视图并将其分配给视图 属性。

【讨论】:

  • 感谢您的评论,但随着更改发生相同的错误。我已经用你建议的更新更新了这个问题。
【解决方案2】:

我没有像这样设置根视图控制器:

    self.window.rootViewController = rootController;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多