加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-14 19:07:02 所属栏目:百科 来源:网络整理
导读:我需要添加一个实例变量和两个使用该实例变量的方法到UIViewController.我在类扩展中为变量添加了一个属性.然后我为UIViewController创建了一个具有方法名称的类别.类别头文件导入类扩展. 要使用该类别,我将在我自己的自定义视图控制器中导入它. 但是,当我调
我需要添加一个实例变量和两个使用该实例变量的方法到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(类别实现)

#import "UIViewController+CustomObject.h"

 @implementation UIViewController (CustomObject)

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

@结束

解决方法

我建议只使用类别和相关对象.

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读