Objective-C新手在这里。
我一直在看这个问题太久了,决定寻求帮助。
我有ViewController和TestClass。我想在ViewController中发出一个名为TestMethod的TestClass方法。来自C#世界我会做:
TestClass testClass = new TestClass();
testClass.TestMethod();
我搜索的时间太长,并没有找到一个简单的解决方案。我发现的所有例子都不起作用或者不符合我的目的。
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];
}
我错过了什么?!?!
答案 0 :(得分:4)
您遗失的内容相当于其中包含new TestClass
的行。
TestClass *testObject = [[TestClass alloc] init];
[testObject testMethod];
另外,将您的方法声明放入TestClass.h接口。
-(void)testMethod;
而且,放一个......是个好主意。
#import "TestClass.h"
...除非绝对必要,否则进入ViewController.m文件而不是.h。