如何从另一个类访问视图控制器的属性

时间:2015-12-10 18:30:14

标签: objective-c properties

我的项目非常简单。我试图了解课程如何相互沟通。它只有一个带按钮的视图控制器。

以下是View Controller文件

//ViewController.h

#import <UIKit/UIKit.h>


@interface ViewController : UIViewController

@property (strong, nonatomic) IBOutlet UIButton *theButton;

@property int clickCount;

- (IBAction)basicAction:(id)sender;

@end



//ViewController.m

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {

    [super viewDidLoad];

    self.clickCount = 0;

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (IBAction)basicAction:(id)sender {

    self.clickCount ++;
    NSLog(@"Click count now = %d", self.clickCount);

}
@end

因此,当您点击按钮时,我们会看到计数上升。我创建了一个名为AnotherClass的新类,它有一个方法。以下是文件:

1 //AnotherClass.h
2
3 #import <Foundation/Foundation.h>
4 #import"ViewController.h"
5 
6 @interface AnotherClass : NSObject
7
8
9 -(void)theMethod;
10
11 @end
12
13 //AnotherClass.m
14
15 #import "AnotherClass.h"
16
17 @implementation AnotherClass
18
19 -(void)theMethod{
20   if(ViewController.clickCount < 5){             
21 do something...
22 } else { do something else...}
23 }
24   @end

超级简单的东西。但是它没有从第20行的ViewController类中识别出属性clickCount。它通过“self”访问它自己的h文件。符号。我已经在标头中导入了ViewController.h,据我所知,您需要做的就是访问其他类属性和方法。是吗?

帮助表示赞赏。

1 个答案:

答案 0 :(得分:0)

您没有获得值的原因是因为AnotherClass尝试访问clickCount作为静态而不是实例变量。您需要通过ViewController中的某种方法获取AnotherClass的实例。假设您将ViewController设置为根视图控制器,您可以使用下面的代码来获取点击次数。

ViewController *controller = (ViewController*)[UIApplication sharedApplication].keyWindow.rootViewController;
if (controller.clickCount < 5) {
    ...
}

请注意,您必须先将UIViewController转换为ViewController,然后从控制器变量中读取clickCount。

相关问题