Objective-C: How to access methods in other classes

Posted by Adam on Stack Overflow See other posts from Stack Overflow or by Adam
Published on 2010-03-22T13:48:40Z Indexed on 2010/03/22 13:51 UTC
Read the original article Hit count: 340

Filed under:

I have what I know is a simple question, but after many searches in books and on the Internet, I can't seem to come up with a solution. I have a standard iPhone project that contains, among other things, a ViewController. My app works just fine at this point.

I now want to create a generic class (extending NSObject) that will have some basic utility methods. Let's call this class Util.m (along with the associated .h file).

I create the Util class (and .h file) in my project, and now I want to access the methods contained in that class class from my ViewController.

Here's an example of a simple version of Util.h

#import <Foundation/Foundation.h>

@interface Util : NSObject {

}

- (void)myMethod;

@end

Then the Util.m file would look something like this:

#import "Util.h"

@implementation Util

- (void)myMethod {
    NSLog(@"myMethod Called");
}

@end

Now that my Util class is created, I want to call the "myMethod" method from my ViewController. In my ViewController's .h file, I do the following:

#import "Util.h"

@interface MyViewController : UIViewController {

    Util *utils;

}

@property (assign) Util *utils;

@end

Finally, in the ViewController.m, I do the following:

#import "Util.h"

@implementation MyViewController

@synthesize utils;

- (void)viewDidLoad {
    [super viewDidLoad];

    utils.myMethod;  //this doesn't work
    [utils myMethod]; //this doesn't work either
    NSLog(@"utils = %@", utils);  //in the console, this prints "utils = (null)"
}

What am I doing wrong? I'd like to not only be able to directly reference other classes/methods in a simple util class like this, but I'd also like to directly reference other ViewControllers and their properties and methods as well.

I'm stumped! Please Help.

© Stack Overflow or respective owner

Related posts about objective-c