forward protocol @required to subclasses
I have:
@interface SuperClass : UIViewController <UITableViewDelegate,UITableViewDataSource>
And then
@interface SubClass : SuperClass
This SuperClass
does not have the required protocol methods implemented SubClass
one does.开发者_StackOverflow
Instead of implementing empty/nil methods in SuperClass
, can the @required warnings validation be made against SubClass
?
You might not declare protocol adoption in the superclass, but demand compliance in all subclasses. This can be done by implementing +initialize
in your superclass as follows:
+ (void)initialize
{
if (self != [SuperClass class] &&
![self conformsToProtocol:@protocol(UITableViewDelegate)])
{
@throw [NSException ...]
}
}
That way, whenever a subclass of SuperClass
is initialized, it will throw an exception if it doesn't conform to <UITableViewDelegate>
. This requires no further work after putting this in the superclass.
No, what you're asking for is essentially abstract classes, which don't exist in Objective-C.
Your best bet is to stub the methods in the base class to throw an exception of some kind.
If SuperClass
is not conform to the UITableViewDelegate
, etc. protocols it should not have it in the .h.
You can simply move the protocols to SubClass
.
Yes this is possible using a private class extension.
Example 1
Superclass.h
@interface Superclass : UIViewController
@end
Superclass.m
@interface Superclass()<UITableViewDelegate, UITableViewDataSource>
@end
@implementation Superclass
// implement interface methods
@end
Subclass.h
@interface Subclass : Superclass<UITableViewDelegate, UITableViewDataSource>
@end
Taking it a step further, you could move the private class extension into a private header Superclass+Private.h then your other internal classes can know it implements them too.
Example 2
Superclass+Private.h
#import "Superclass.h"
@interface Superclass()<UITableViewDelegate, UITableViewDataSource>
@end
Superclass.m
#import "Superclass+Private.h>
@implementation Superclass
// implement interface methods
@end
Note There is a limitation that this technique prevents you overriding and calling super in method that the subclass does not its super class has implemented. For those methods I would recommend the UIGestureRecogniser subclass pattern.
精彩评论