tags:

views:

45

answers:

2

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.

+1  A: 

You just need to create the actual object.

Your implementation only defines a pointer to an Util object but it still points to nil.

utils = [[Util alloc] init];

An alternative is to create static methods by replacing - by + in the method prefix.

[Util myMethod];
mouviciel
Thanks for the reply on this. This fixes the problem I was having.
Adam
+1  A: 

You should probably take a look at one of the many Objective C tutorials, but the direct answer to your question is that you have not allocated and initialised an instance of your object. The code should look like:

utils = [[Utils alloc] init];
[utils myMethod];
Stephen Darlington
Thank you. I knew it was a simple problem, but for some reason I was thinking that @synthesize would also perform init for me. Obviously it doesn't. This fixed my issue. Thanks again.
Adam