なぜmixinが必要なのか?
ベースとなるViewControllerに共通の変数+メソッドを追加したかった
- UIViewController
- UITableViewController
- UICollectionViewController
カテゴリ+AssociatedObjectでも出来なくはないけど、面倒。
実現方法
mixin定義をoptionalなprotocolとして定義し、それを実装するmixin用オブジェクトを定義する。
@protocol SampleMixinProtocol<NSObject>
@optional
@property BOOL aBool;
@end
@interface SampleMixin : NSObject<SampleMixinProtocol>
@end
インスタンス変数としてmixinオブジェクトを持つようにし、必要に応じてメソッド呼び出しをフォワードする。
#mixinオブジェクトの生成コードは省略しています。
@interface SampleViewController : UIViewController<SampleMixinProtocol>
@property SampleMixin *mixin;
@end
@implementation SampleViewController
- (void)setValue:(id)value forUndefinedKey:(NSString *)key
{
[self.mixin setValue:value forKey:key];
}
- (id)valueForUndefinedKey:(NSString *)key
{
return [self.mixin valueForKey:key];
}
- (void)forwardInvocation:(NSInvocation*)inv {
if ([self.mixin respondsToSelector:[inv selector]]) {
[inv invokeWithTarget:self.mixin];
} else {
[super doesNotRecognizeSelector:[inv selector]];
}
}
- (NSMethodSignature*)methodSignatureForSelector:(SEL)sel {
return [self.mixin methodSignatureForSelector:sel];
}
@end
ちゃんとコード補完も効くので、ほぼmixinっぽく使えています。