Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Putting methods in separate files

I have a class (MyClass) with a lot of methods. Consequently, the .m file has become quite difficult to read. I'm relatively new to Objective-C (having come from REALbasic) and I was wondering if it's possible to put some of the methods in MyClass into different files and then include them in the class. How would I go about this in Xcode?

like image 348
Garry Pettet Avatar asked Dec 10 '22 15:12

Garry Pettet


2 Answers

Yes it is possible and fortunately this can be done easily in Objective-C with Categories.


Say you have your base class MyClass.

@interface MyClass : NSObject
-(void) methodA;
@end

And the according implementation file (not relevant here).

Then you can create a category by defining a new interface in a new header file:

// the category name is in parenthesis, can be anything but must be unique
@interface MyClass (extended) 
-(void) methodB;
@end

and the implementation file:

@implementation MyClass (extended)
-(void) methodB {

}
@end

Common convention to name these files is ClassToAddMethodsTo+CatgoryName, i.e.:

MyClass+extended.h
MyClass+extended.m

Group related functionality into categories and give it a meaningful name.

like image 95
Felix Kling Avatar answered Jan 01 '23 11:01

Felix Kling


In Objective-c you can break a class into 'categories' - a class spread across many files. The normal Object-Oriented way is to use SuperClasses and SubClasses.

This is almost certainly a code smell telling you that you have a design problem. See this antipattern

like image 22
hooleyhoop Avatar answered Jan 01 '23 11:01

hooleyhoop