-5

我有个问题。我想我不明白一些事情。

我有一个带有变量和方法的类。

  • AppDelegate.h/.m
  • WifiMon.h./m <-- 上面提到的那个
  • 视图控制器.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
}

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

但为什么?

4

2 回答 2

1

当你在 C 中声明一个变量时,它只存在于它被声明的范围内。如果在函数内声明它,它只存在于该函数内

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

@interface ViewController : UIViewController {
    WifMon *test;
}

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

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

@interface ViewController : UIViewController

@property (strong) WifMon *test;

...

@end

然后您可以使用self.test.

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

于 2013-06-03T11:30:46.753 回答
1

变量的范围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];
}
于 2013-06-03T11:31:30.853 回答