5

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];
 }

@終わり

4

1 に答える 1

1

代わりに、カテゴリと関連オブジェクトのみを使用することをお勧めします。

UIViewController+CustomObject.h

#import <UIKit/UIKit.h>
#import "CustomObject.h"

@interface UIViewController (CustomObject)
@property (nonatomic, strong) CustomObject *customObject;

- (void)customMethod;

@end

UIViewController+CustomObject.m

#import <objc/runtime.h>
#import "UIViewController+CustomObject.h"

static char customObjectKey;

@implementation UIViewController (CustomObject)

- (CustomObject *)customObject{
    CustomObject *_customObject= objc_getAssociatedObject(self, &customObjectKey);
    return _taskDateBarView;
}

- (void)setCustomObject :(CustomObject *)_customObject{
    objc_setAssociatedObject(self, &customObjectKey, _customObject, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (void)customMethod
{
     [self.customObject doSomething];
}

@end
于 2013-02-06T11:42:19.483 に答える