在按钮操作方法中运行实例方法



我有一个问题。我想我不会解开一些东西。

我有一个类,有变量和一个方法。

  • AppDelegate.h/.m
  • WifMon.h./m <-- 上面提到的那个
  • ViewController.h./m

所以现在我在我的ViewController.m中创建了一个WifMon的实例(包括WifMon的标头。

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    WifMon *test = [[WifMon alloc] initWithData:"google.de" withPort:443];
}

不,我有一个按钮,想开始我的"dynCheck"方法。

- (IBAction)startCheck:(id)sender {
    //start dynCheck here
    [test dynCheck];       //this isn't working
}

但这行不通。我无法在操作方法中访问我的"测试"实例。

但是为什么?

变量test的作用域仅在viewDidLoad方法中有效。

为了克服这个问题,你需要一个实例变量。最好是test周围的物业。

@interface ViewController ()
@property (nonatomic, strong) WifMon* test;
@end
@implementation ViewController
- (void)viewDidLoad
{
    [super viewDidLoad];
    self.test = [[WifMon alloc] initWithData:"google.de" withPort:443];
}
- (IBAction)startCheck:(id)sender
{
    //start dynCheck here
    [self.test dynCheck];
}

如果您不使用 ARC,请注意!!如果不是,你应该

self.test = [[[WifMon alloc] initWithData:"google.de" withPort:443] autorelease];

- (void)dealloc
{
    [super dealloc];
    [_test release];
}

当你在 C 中声明一个变量时,它只存在于声明它的作用中。如果在函数中声明它,则它仅存在于该函数中

如果您希望能够从对象的所有实例方法访问它,则需要将test声明为类中的实例变量:

@interface ViewController : UIViewController {
    WifMon *test;
}

然后test将在对象的所有实例方法中可用。

或者,

如果您希望实例变量可由其他对象访问,或者能够使用 self.test 访问它,您可以像这样声明它:

@interface ViewController : UIViewController
@property (strong) WifMon *test;
...
@end

然后您可以使用 self.test .

请注意,此示例使用的是 ARC(默认情况下已启用,因此您可能已经在使用它(,但如果您不是,则需要将属性声明为 retain 而不是 strong ,并记住在 dealloc 方法中释放test

最新更新