类扩展中变量属性的自动合成

5

我需要在UIViewController中添加一个实例变量和两个使用该实例变量的方法。我在类扩展中为该变量添加了一个属性。然后我为UIViewController创建了一个包含方法名称的分类。该分类头文件导入了类扩展。

要使用该分类,我将其导入到我的自定义视图控制器中。但是,当我调用其中一个使用扩展中声明的属性的分类方法时,它会崩溃。

我可以通过在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(分类实现)

@end

 #import "UIViewController+CustomObject.h"

 @implementation UIViewController (CustomObject)

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

@end


这里有一个非常清晰的例子:http://developer.apple.com/library/ios/#documentation/cocoa/conceptual/objectivec/chapters/occategories.html - danh
看起来你试图将一个类扩展当作单例来处理。 - AMayes
你确定不能直接继承UIViewController吗? - Bryan Chen
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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接