Bobby Turkalino
Bobby Turkalino

Reputation: 111

Objective-C access another class

Objective-C newbie here.

I've been looking at this for way too long and decided to ask for help.

I have ViewController and TestClass. I want to message a method from TestClass called TestMethod in ViewController. Being from the C# world I would do:

TestClass testClass = new TestClass(); 
testClass.TestMethod();

I've searched for too long and haven't found a simple solution. All of the examples I've found either don't work or don't fit what I'm trying to do.

TestClass.h

#import <Foundation/Foundation.h>

@interface TestClass : NSObject

@end

TestClass.m

#import "TestClass.h"

@implementation TestClass

-(void)testMethod {

}

ViewController.h

#import "TestClass.h"

@interface ViewController : UIViewController

ViewController.m

#import "ViewController.h"

TestClass *testClass;

@interface ViewController()

@end

@implementation ViewController

-(void)viewDidLoad {
    [testClass testMethod];
}

What am I missing?!?!

Upvotes: 0

Views: 40

Answers (1)

Phillip Mills
Phillip Mills

Reputation: 31026

What you're missing is the equivalent of the line with new TestClass in it.

TestClass *testObject = [[TestClass alloc] init];
[testObject testMethod];

Also, put a declaration of your method into the TestClass.h interface.

-(void)testMethod;

And, it's a good idea to put...

#import "TestClass.h"

...into your ViewController.m file instead of your .h unless absolutely necessary.

Upvotes: 4

Related Questions