views:

224

answers:

2

I'm making a simple program in Objective-C. It has one class with a lot of methods. I'd just like to put the methods in another file... so I could move the following

- (void) myfunc1 {...}
- (void) myfunc2 {...}
// more functions

to another file and replace the above w/ something like

#include "myNewFile.something"

I'm fine w/ putting the #include (or whatever) statement just right in the original file.

How can I do this?

A: 

You need to create a header file and include it as appropriate.

If you move all your code to "newFile.m", create "newFile.h" and put all your method signatures in the header file. Then in your old file, do "#include oldFile.h".

samoz
+1  A: 

You'll need to split your methods in to different "categories," which each get their own h and m files. You'll also need an h and m file for the class itself. Here's a simple little example that I think will show you what you need to do.

TestClass.h

#import <Cocoa/Cocoa.h>
@interface TestClass : NSObject {
}
@end

TestClass.m

#import "TestClass.h"
@implementation TestClass
@end

TestClass+Category1.h

#import <Cocoa/Cocoa.h>
#import "TestClass.h"
@interface TestClass(Category1) 
-(void)TestMethod1;
@end

TestClass+Category1.m

#import "TestClass+Category1.h"
@implementation TestClass(Category1)
-(void)TestMethod1 {
NSLog(@"This is the output from TestMethod1");
}
@end

TestClass+Category2.h

#import <Cocoa/Cocoa.h>
#import "TestClass.h"
@interface TestClass(Category2) 
-(void)TestMethod2;
@end

TestClass+Category2.m

#import "TestClass+Category2.h"
@implementation TestClass(Category2)
-(void)TestMethod2 {
NSLog(@"This is the output from TestMethod2");
}
@end

Then in whatever file is using your class, you'll use

#import "TestClass.h"
#import "TestClass+Category1.h"
#import "TestClass+Category2.h"

Now you can create an instance of class TestClass and it will have all the methods from both category1 and category2. Simply use

TestClass* test = [[TestClass alloc] init];
[test TestMethod1];
[test TestMethod2];
Warren Pena