【问题标题】:WebView being released too many timesWebView 被释放太多次
【发布时间】:2014-02-28 14:21:37
【问题描述】:

我正在尝试在 WebView 中加载网页以获取网站的快照。 WebView 包含在我为此目的创建的临时窗口中。但是,在我释放 WebView 和临时窗口后不久,WebView 被发送另一个释放消息,而它已经被释放。这是调试器中的错误消息,其中 NSZombieEnabled 设置为 YES。

*** -[WebView release]: message sent to deallocated instance 0x608000125820

我无法弄清楚是什么导致 WebView 被释放太多次。使它更加混乱的是,问题仅在加载某些 URL 时发生。例如:尝试拍摄http://www.google.com 的快照时一切正常,但使用http://edition.cnn.com 时几乎总是崩溃。

代码如下(简化版):

@interface AppDelegate ()

@property (nonatomic, strong) NSWindow *tempWindow;
@property (nonatomic, strong) WebView *webView;

@end

@implementation AppDelegate

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
    CGRect frame = CGRectMake(0, 0, 1200, 695);
    self.tempWindow = [[NSWindow alloc] initWithContentRect:frame styleMask:NSBorderlessWindowMask backing:NSBackingStoreBuffered defer:NO];
    self.webView = [[WebView alloc] initWithFrame:frame];
    self.webView.frameLoadDelegate = self;

    self.tempWindow.contentView = self.webView;

    [[self.webView mainFrame] loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://edition.cnn.com"]]];
}

#pragma mark - WebFrameLoadDelegate

- (void)webView:(WebView *)sender didFinishLoadForFrame:(WebFrame *)frame
{
    if (frame != [sender mainFrame]) {
        return;
    }

    // take snapshot here...
    [self takeSnapshot];

    // get rid of web view and temp window
    [self.webView stopLoading:nil];
    [self.webView setFrameLoadDelegate:nil];

    self.webView = nil;
    self.tempWindow = nil;
}

【问题讨论】:

    标签: objective-c macos webkit foundation


    【解决方案1】:

    使用 ARC 时,在某些情况下保留/释放 WebView 似乎存在问题。从我的测试中我发现在释放之前在WebViewmainFrame 中加载一个空的NSString 应该可以解决问题。

    另请参阅short blog entry on this topic

    【讨论】:

    • 我保持对 web 视图的强烈引用,我将其设置为 nil 以演示问题。即使我不保留对 web 视图的强引用,也会出现问题
    • 我有一个非常相似的设置,并且 WebView 很弱,它可以正常工作而不会崩溃或泄漏,所以一定有别的东西。
    • 您是否使用 javascript 委托或类似的委托?我发现这可能会导致保留:batsonar.blogspot.de/2013/01/webview-and-arc.html - 因此,如果一次被保留而一次不被额外保留,则可以解释显示的行为。
    • 谢谢!当我在取消 Web 视图之前使用空字符串调用 loadRequest 时,就像您在博客文章中建议的那样,它可以工作。如果您编辑答案以包含此解决方案,我会将其标记为已解决。
    • 感谢您的跟进,很高兴它也对您有用。我花了一些时间再次记住我自己的博客文章...
    猜你喜欢
    • 1970-01-01
    • 2014-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-27
    • 2018-02-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多