【问题标题】:access to property of another class访问另一类的财产
【发布时间】:2012-05-17 09:11:01
【问题描述】:

如何从另一个类访问 ViewController 属性?
(ViewController 是由 XCode 创建的)

这是 ViewController.h 的代码:

#import <UIKit/UIKit.h>
#import "AppDelegate.h"

@interface ViewController : UIViewController{
    AppDelegate *appDelegate; //il delegate disponibile per tutta la classe
    int numPag; //indice array (sulle pagine html da visualizzare)

    NSString *path;
    NSURL *baseURL;

    NSString *file;
    NSString *contentFile;

}


- (IBAction)sottrai:(id)sender;

- (IBAction)aggiungi:(id)sender;



@property (strong, nonatomic) IBOutlet UILabel *valore;
@property (strong, nonatomic) IBOutlet UIWebView *web;

@end

谢谢!

[编辑]

我使用 Xcode 4.3.2 并且 AppDelegate.m 的代码找不到类似的东西:

self.viewController = [[ViewController alloc] initWithNibName:@"ViewController" bundle:nil];

现在,我在方法 didFinishLaunchingWithOptions:(into AppDelegate.m) 中放入了这段代码:

    viewController = [[UIViewController alloc] initWithNibName:@"ViewController" bundle:nil];

[viewController.web loadHTMLString:contentFile baseURL:baseURL];  

在文件 AppDelegate.h 中添加变量 viewController:

#import <UIKit/UIKit.h>

@interface AppDelegate : UIResponder <UIApplicationDelegate>{
    NSArray *pageInItalian;
    NSArray *pageInEnglish;
    UIViewController *viewController; 

}

@property (strong, nonatomic) NSArray *pageInLanguage;
@property (strong, nonatomic) UIWindow *window;



@end

我做得对吗?错误是:在“UIViewController *”类型的对象上找不到属性“web”

【问题讨论】:

    标签: objective-c xcode4


    【解决方案1】:

    我认为这篇文章可能会回答你的问题

    How can I access variables from another class?

    您需要使您的变量可以从外部类(使用@property 和@synthesize)访问,然后您的外部类需要知道您的 ViewController 实例

    [编辑]

    在您的 AppDelegate.m 中,必须有这样一行:

    self.viewController = [[ViewController alloc] initWithNibName:@"ViewController" bundle:nil];
    

    这是您的 ViewController 实例化的地方。从那里,您可以访问 ViewController 的每个属性。

    [编辑]

    您需要在实施开始时添加以下内容

    @implementation ViewController
    
    @synthesize web;
    

    【讨论】:

    • 如何获取 ViewController 的实例?视图控制器是由 XCode 在代码中创建的。我可以实例化它吗?
    • 我已经做到了。我在哪里做错了?...我无法分配“ViewController”,只能理解“UIViewController”。也许这是错误
    最近更新 更多