ios – 即使有delegate = self,uiwebview也没有加载请求

前端之家收集整理的这篇文章主要介绍了ios – 即使有delegate = self,uiwebview也没有加载请求前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我创建了一个NSObject类并包含在init中创建一个uiwebview,将委托设置为self并发送加载请求.

由于某种原因,webViewDidFinishLoad或didFailLoadWithError永远不会被触发.我无法理解为什么.

//
//  RXBTest.h
#import <Foundation/Foundation.h>
@interface RXBTest : NSObject <UIWebViewDelegate>
@end
//  RXBTest.m
//  pageTest
#import "RXBTest.h"
@implementation RXBTest
- (id) init
{
     if((self=[super init])){
         UIWebView* webView = [[UIWebView alloc] initWithFrame:CGRectMake(0,320,320)];
         [webView setDelegate:self];

         [webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.google.com/"]]];
     }
     return self;
}   
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error{
     NSLog(@"ERROR LOADING WEBPAGE: %@",error);
}
- (void) webViewDidFinishLoad:(UIWebView*)webView
{
     NSLog(@"finished");
}
@end

有人有什么想法吗?

谢谢
鲁迪

解决方法

如果您使用的是ARC,那么问题是您的webView变量是init方法的本地变量,因此在Web视图完成加载之前会被取消分配.尝试将Web视图添加为实例变量:

@interface RXBTest : NSObject <UIWebViewDelegate>
{
    UIWebView* webView;
}
@end

@implementation RXBTest
- (id) init
{
    if((self=[super init])){
        webView = [[UIWebView alloc] initWithFrame:CGRectMake(0,320)];
        [webView setDelegate:self];

        [webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.google.com/"]]];
    }
    return self;
}
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error{
    NSLog(@"ERROR LOADING WEBPAGE: %@",error);
}
- (void) webViewDidFinishLoad:(UIWebView*)webView
{
    NSLog(@"finished");
}
@end

如果您不使用ARC,则需要记住在dealloc方法中释放webView对象.

猜你在找的Xcode相关文章