Reputation: 12650
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;
}
Upvotes: 0
Views: 626
Reputation: 4725
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.
Upvotes: 3