Tuesday, May 11, 2010

Calling methods in another class file

Now that I have my app doing quite a few things I'm starting to realize that I should have created one central place to put a bunch of functions and then call them from different views. So, I spent some time in google (because I don't have any iPhone programming books, nor do I know how to program object oriented stuff) and found a few different way to do this. Actually, they are just variations of the same thing. I'll show how I'm doing it in my code now.

In the YourFunctions.h file of the new class:

- (void) showAlert:(int)errorNumber;

In the YourFunctions.m file of the new class:

- (void) showAlert:(int)errorNumber {

UIAlertView *error = [[UIAlertView alloc] initWithTitle:[[NSString alloc] initWithFormat:@"Error: %D", errorNumber]

message:[[NSString alloc] initWithFormat:@"This is an error"]



otherButtonTitles: nil];

[error show];

[error release];


In the YourView.m file you are calling this new method from:

#import "YourFunctions.h"

// As a test I attached a button to this action.

- (IBAction)showAnAlert {

int errorNumber = 22;

YourFunctions *yourFunctions = [[YourFunctions alloc] init];

[yourFunctions showAlert:errorNumber];


No comments: