iPhone: Share a Single Function but Extend Different Classes
Hey is it possible for muliple objects to share a single function but extend different classes? Cause I would rather not have to rewrite my code over and over. Here is an example of what I would do without said method:
I want to have a single, method without having to call [MovieClip loadLandscape];
in the Timeline Implementation
RotatingProtocol.h
@protocol Rotat开发者_StackOverflowingProtocol
@required
- (void)loadPortrait;
- (void)loadLandscape;
@end
MovieClip.h
#import "RotatingProtocol.h"
@interface MovieClip : UIButton <RotatingProtocol> {
}
@end
MovieClip.m
#import "MovieClip.h"
@implementation MovieClip
- (void)loadPortrait {
// UIButton -> setframe to fit portrait screen
}
- (void)loadLandscape {
// Popup and alert!
}
@end
Timeline.h
#import "RotatingProtocol.h"
@interface Timeline : UIScrollView <RotatingProtocol> {
}
@end
Timeline.m
#import "Timeline.h"
@implementation Timeline
- (void)loadPortrait {
// Do funny animation
}
- (void)loadLandscape {
// Do exactly the same thing as [MovieClip loadLandscape]
}
@end
One possible solution, that I hesitate to recommend, is to provide a category on UIView (the highest level superclass both classes share) that adds the loadLandscape method implementation, then you could leave it out of the objects and just declare the class supports that protocol (and also import the category).
That's kind of extreme since every UIView instance gets the method that could be called, which might confuse something that checks for respondsToSelector instead of conformsToProtocol.
The technique I'd use is to put that implementation into something like a RotatingProtocolImplementation class as a class level method. Something has to know to call the loadLandscape method of your protocol, and that something could just as easily detect the class declared support for the protocol and call the shared class level method instead of a method on the class instance itself - so the protocol could become more of a marker protocol, without as many (or any) methods a class would have to define to support it.
精彩评论