Search code examples
objective-cinstances

Using an allocated and initialised object outside of viewDidLoad?


I hope the question title is adequate

Just confused about something in a piece of code I have seen in an online tutorial. There is a generic ZHEDog class with declared properties, methods, etc. and from this class we have created several instances - firstDog, secondDog, fourthDog, and so on.

Now, when we created each instance we did so inside of the viewDidLoad method of our main(one)view controller with the line:

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

and then we set some of its properties like name, and so on, here after this line.

So we did this instance creation in the view controller's viewDidLoad and so far have not subclassed the generic ZHEDog class, so it is all deriving from the one class file.

Now, where I am confused is that apparently I cannot set a property of this instance in another method (other than viewDidLoad), so I can't say something like:

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

It kind of makes sense but I can't explain why. I would have thought once the instance was allocated and initialised I could change its properties where I wanted to if necessary? But do the same rules of scope apply to viewDidLoad?


Solution

  • Use properties, they are like instance variables accessible from everywhere within the instance of the class

    @property ZHEDog *firstDog, *fourthDog;
    

    then instantiate them in viewDidLoad

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

    and change them in a method

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