1 つのインスタンス変数と、そのインスタンス変数を使用する 2 つのメソッドを UIViewController に追加する必要があります。クラス拡張に変数のプロパティを追加しました。次に、メソッド名を持つ UIViewController のカテゴリを作成しました。カテゴリ ヘッダー ファイルは、クラス拡張をインポートします。
カテゴリを使用するには、独自のカスタム ビュー コントローラーにインポートします。ただし、(拡張機能で宣言されたプロパティを使用する) カテゴリ メソッドの 1 つを呼び出すと、クラッシュします。
UIViewController のサブクラスでプロパティを合成することでこれを回避できますが、これらは自動的に合成する必要があると考えました。
何か不足していますか?
UIViewController_CustomObject.h (拡張ヘッダー)
#import <UIKit/UIKit.h>
#import "CustomObject.h"
@interface UIViewController ()
@property (nonatomic, strong) CustomObject *customObject;
@end
UIViewController+CustomObject.h (カテゴリ ヘッダー)
#import <UIKit/UIKit.h>
#import "UIViewController_CustomObject.h"
@interface UIViewController (CustomObject)
- (void)customMethod;
@終わり
UIViewController+CustomObject.m (カテゴリの実装)
#import "UIViewController+CustomObject.h"
@implementation UIViewController (CustomObject)
- (void)customMethod
{
[self.customObject doSomething];
}
@終わり