在viewDidLoad之外使用已分配和初始化的对象?

时间:2015-07-17 15:37:19

标签: objective-c instances

我希望问题标题足够

对于我在在线教程中看到的一段代码中的某些内容感到困惑。有一个通用的ZHEDog类,它有声明的属性,方法等。从这个类我们创建了几个实例 - firstDog,secondDog,fourthDog等。

现在,当我们创建每个实例时,我们在主(一个)视图控制器的viewDidLoad方法中使用以下行完成:

ZHEDog *fourthDog = [[ZHEDog alloc] init];

然后我们设置它的一些属性,比如名称,依此类推,在这一行之后。

所以我们在视图控制器的viewDidLoad中创建了这个实例,到目前为止还没有子类化通用的ZHEDog类,所以它都来自一个类文件。

现在,我感到困惑的是,显然我无法在另一种方法(viewDidLoad除外)中设置此实例的属性,因此我无法说出类似的内容:

-(void) printHelloWorld
{
fourthDog.name = "something new";
}

这有点意义,但我无法解释原因。我会想到,一旦实例被分配并初始化,我可以根据需要更改其属性吗?但是,相同的范围规则是否适用于viewDidLoad?

2 个答案:

答案 0 :(得分:1)

使用属性,它们就像可以在类

的实例中的任何位置访问的实例变量
b

然后在@property ZHEDog *firstDog, *fourthDog;

中实例化它们
viewDidLoad

并在方法中更改它们

self.firstDog = [[ZHEDog alloc] init];
self.fourthDog = [[ZHEDog alloc] init];

答案 1 :(得分:1)

@vadian有什么是正确的,但使用属性也允许其他类看到这个变量。假设您导入了头文件并且它包含@property ZHEDog *firstDog, *fourthDog;。这些变量变得公开。除非他们在植入文件中。

但其他方法是创建如下变量:

标题文件

@interface ViewController : UIViewController {
    ZHEDog *firstDog, *fourthDog;

}

@end

现在,只有ViewController的值是私有或独占的,所有这些都是相同的。因此不允许他人使用或看到这些变量。并访问函数 printHelloWorld

中的变量
- (void)printHelloWorld {
    firstDog.name = @"woof";       
    fourthDog.name = @"something new";

}

<强>清分

- (void)viewDidLoad {
    //new is the combination of alloc and init. only use +new when using alloc and init, not alloc and initWith...
    firstDog = [ZHEDog new];
    fourthDog = [ZHEDog new];

}

我希望这会改善你的目标:)