0

I'm new to Objective-C, so I may be way off...

I have this in my 'viewDidLoad' method:

NSArray *myArray;
NSString *cow = @"Cow";
NSString *pig = @"Pig";
NSString *frog = @"Frog";
NSString *sheep = @"Sheep";
myArray = [NSArray arrayWithObjects: cow, pig, frog, sheep, nil];
randomNumber.text = [myArray objectAtIndex: arc4random() % (4)];    

I want to make this its own method, so I can get a random animal any time I want...but I need this to happen when the program starts. How do I access a method like this?

I may be way wrong, so I'm open to suggestions, corrections, and anything you think is helpful.

Like this:

- (void)generateAnimal{
    NSArray *myArray;
    NSString *cow = @"Cow";
    NSString *pig = @"Pig";
    NSString *frog = @"Frog";
    NSString *sheep = @"Sheep";
    myArray = [NSArray arrayWithObjects: cow, pig, frog, sheep, nil];
    randomNumber.text = [myArray objectAtIndex: arc4random() % (4)];    
}

Also:

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    self generateAnimal;


}
0

2 Answers 2

3

As Sagi mentioned before, in this case [self generateAnimal]; would have the wanted effect. In general Objective-C (as any other object oriented language) attaches methods to classes/instances, so you can only call them on existing instances. (Obviously there are class methods etc, but more abstractly speaking)

Objective-C wants you to enclose these calls to methods in square brackets ([ ]), as seen both in Sagi's answer and in your own example ([super viewDidLoad]). All the calls follow this pattern [target method: parameter]. Hope it makes sense, just wanted to add a bit of context to Sagi's answer.

Sign up to request clarification or add additional context in comments.

Comments

1
[self generateAnimal]; //would work great :)

4 Comments

Ah. The method has to be before when it is called?
PS: Is there a better way to make an array of strings?
No, your code is just dandy, except you didn't enclose your method in square braces "[ ]".
Here's another quick question: How do I keep it from picking a random animal that is the same as a current animal? Doing this with only four variables makes it pretty likely that the same animal could be picked several times in a row.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.