At some point along my iPhone learning curve, I had to recall some basic principles of object oriented programming — like calling a method from one class to another to pass data. For some reason, using MVC, I was trying to store data objects centrally, assuming all classes would have access to that data. This proved harder than one would imagine. When I finally figured out how to access and call methods in between classes, passing data got much easier.
The code below shows how to:
– Create an instance of another class within a class
– Call a method of another class
– Pass a variable to a method of another class
First, you need to include the header of the ‘other’ class whose method you want to call:
#import "ThisViewClass.h"
#import "OtherViewClass.h"
@implementation ThisViewClass
.
Second, you need to create an instance of that ‘other’ class and call the method, passing the parameter (variable) when needed. This assumes the method you are calling in the other class is inside the view. Otherwise, drop the ‘.view’:
- (void) insideSomeMethod {
[(OtherViewClass *)self.view setName:@"chuckstar"];
}
In the ‘other’ class, here’s how the method you’re calling appears:
- (void) setName:(NSString *)name {
coolPerson.text = name;
}
Lastly, you’ll need to expose that method in the class header:
.
@interface OtherViewClass : UIViewController {
.
}
- (void) setName:(NSString *)name;
@end
Of course, there are other ways to reference the ‘other’ class instance, like adding it as a view using initWithNibName. I’ll take a look at that in a future post.
If you’ve got a better, more efficient way of doing the above, please feel free to comment.
Thanks Chuck! I was spinning my wheels with this one trying something like:
Helper *helper = [[Helper alloc] init];
helper.mymethodcall;
[helper release];
And it just gave me errors. Thanks for the elegant solution!
Thanks Chuck. i’ve tried to call method from the other class according to your way, but it hangs. any comments for this??
@interface EAControlClass : NSObject {
unsigned char test_1;
}
– (unsigned char) GetConnectedStatus;
@end
@implementation EAControlClass
– (unsigned char) GetConnectedStatus
{
test_1 = 100;
return test_1;
}
@end
TimerTick method to call GetConnectedStatus() in the other class.
#import “EAControlClass.h”
-( void ) TimerTick
{
unsigned char received_data;
received_data = [(EAControlClass*)self GetConnectedStatus];
}