LoginSignup
13
13

More than 5 years have passed since last update.

Objective Cでmixin

Posted at

なぜ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っぽく使えています。

13
13
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
13
13