如何从 objective c 中的另一个函数访问实例?

How to access instance from another function in objective c?

我正在尝试从另一个 class.

访问一个 webView 对象

viewController.m

    @property (strong, nonatomic) TOWebViewController *webViewController;

    @end

    @implementation ViewController

    - (void)viewDidLoad {

            [super viewDidLoad];

            self.webViewController = [[TOWebViewController alloc]  initWithURLString:[NSString stringWithFormat:@"http://www.%@/", url] ];

            [self setViewControllers:@[_webViewController]];

        }

- (void)request {

     NSURL *url=[NSURL URLWithString:@"http://www.google.com"];

     NSURLRequest *request=[NSURLRequest requestWithURL:url];

     [_webViewController.webView loadRequest:request];

 }

TOWebViewController 有 webView 属性 来访问 webview。当调用 (void)request 时,开始加载某些内容,但不会将其加载到在 viewDidLoad 中创建的 webview 中。我如何让它在 (void) 请求中引用正确的 webViewController?

你应该尝试使用 childViewController。

参考文档UIViewController Class Reference

以下是您可能需要调用的基本方法:

addChildViewController:

removeFromParentViewController:

willMoveToParentViewController:

didMoveToParentViewController:

我最好的猜测是您真正想要的是在 "parent" 视图控制器中显示 UIWebView,并且不需要 "child" 视图控制器。

为什么不这样做呢?

@interface ViewController : UIViewController

@property (weak) IBOutlet UIWebView *webView; // set outlet in IB

@end

@implementation ViewController

// ...

- (void)request {
     NSURL *url=[NSURL URLWithString: @"http://www.google.com"];
     NSURLRequest *request = [NSURLRequest requestWithURL: url];

     [self.webView loadRequest:request];
}

@end

我刚刚在 github 上查看了 TOWebviewController,它在 TOWebViewController.h 中陈述了以下内容:

/**
 The web view used to display the HTML content. You can access it through this
 read-only property if you need to anything specific, such as having it execute arbitrary JS code.

 @warning Usage of the web view's delegate property is reserved by this view controller. Do not set it to another object.
 */
@property (nonatomic,readonly)  UIWebView *webView;

因此 class 听起来您不需要通过直接访问它来与之交互。

您很可能只想设置 url:

/** 
 Get/set the current URL being displayed. (Will automatically start loading) 
 */
@property (nonatomic,strong)    NSURL *url;

所以尝试:

- (void)request {

     NSURL *url=[NSURL URLWithString:@"http://www.google.com"]

     _webViewController.url = url;

 }