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?
views:
80answers:
2
+7
A:
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.
Felix Kling
2010-05-25 11:30:36
Thank you so much. That's exactly what I was looking for!
Garry
2010-05-25 14:41:36
+4
A:
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
mustISignUp
2010-05-25 11:37:38
Using categories is not *certainly* code smell. E.g. if you want to extend a class for which you do not have the source code. Or if you just want to structure your class in logical blocks. But your right so far, as it is probably code smell if your class has really a lot methods (*god like class*).
Felix Kling
2010-05-25 11:52:10
Hey Felix ***!@ - Having a class so large you can't manage it is the code smell.
mustISignUp
2010-05-25 12:16:10
@mustISignUp: Definitely, and I said your are right in this point. But your answer can also be interpreted that using categories *in general* is code smell. I just wanted to emphasize that it is not.
Felix Kling
2010-05-25 12:21:41
You're right. Categories themselves are very useful for grouping functionality or even extending classes, amongst other things.
mustISignUp
2010-05-25 12:24:16
I see your argument regarding a God-like class. I am bearing this in mind. Having now split my class into separate files using categories though it certainly seems to make a lot more logical sense.
Garry
2010-05-25 14:42:32
You might find this interesting http://en.wikipedia.org/wiki/Single_responsibility_principle
mustISignUp
2010-05-25 15:01:55