iPhone: Sharing protocol/delegate code
I have the following code protocol snippets:
@protocol FooDelegate;
@interface Foo : UIViewController { id delegate; } ...
@protocol FooDelegate ... // method 1 ... // method 2 ... @end
Also, the following code which implements开发者_开发百科 FooDelegate:
@interface Bar1 : UIViewController { ... }
@interface Bar2 : UITableViewController { ... }
It turns out the implementation of FooDelegate is the same on both Bar1 and Bar2 classes. I currently just copy FooDelegate implementation code from Bar1 to Bar2.
How do I structure/implement in such a way that Bar1 and Bar2 share the same code in a single code base (not as currently with 2 copies) since they are the same?
Thanks in advance for your help.
Option A: Implement the method in a Category
Any properties used must be declared in UIViewController
.
UITableViewController
is a subclass of UIViewController
.
//UIViewController+MyAdditions.h
@interface UIViewController (MyAdditions)
- (void)myCommonMethod;
@end
//UIViewController+MyAdditions.m
@implementation UIViewController (MyAddtions)
- (void)myCommonMethod {
// insert code here
}
The new method added to UIViewController
will be inherited by Bar1
and Bar2
Option B: Create a MyViewControllerHelper
class
If you can, implement your common code as a class method, otherwise you will need to create an instance of your helper class either temporarily or as a property of Bar1
and Bar2
@interface MyViewControllerHelper : NSObject
- (void)myCommonMethod;
@end
@implementation MyViewControllerHelper
- (void)myCommonMethod {
// common code here
}
@interface Bar1 : UIViewController {
MyViewControllerHelper *helper;
}
@property MyViewControllerHelper *helper;
@end
@implementation Bar1
@synthesize helper;
- (void)someMethod {
[helper myCommonMethod];
}
@end
@interface Bar2 : UITableViewController {
MyViewControllerHelper *helper;
}
@property MyViewControllerHelper;
@end
@implementation Bar2
@synthesize helper;
- (void)someOtherMethod {
[helper myCommonMethod];
}
@end
Make a new object, MyFooDelegate:
@interface MyFooDelegate : NSObject <FooDelegate>
Then Bar1 and Bar2 can each create an instance of it (or share one instance). In those classes you can eliminate the delegate methods and add lines like:
MyFooDelegate *myDooDelegateInstance = ...;
foo.delegate = myFooDelegateInstance;
You could also create an instance of MyFooDelegate in a NIB file and connect the view controller's delegate outlets to it, if desired.
That way, you won't have any duplicated code in your source files or in your executables.
精彩评论