iOS开发技巧之:Category中使用属性的懒加载

2024-06-06  本文已影响0人  VKOOY
@interface VC (Pay)
@property (nonatomic, strong) PayView *choiceView;
@end

两种写法:
1,使用指针

#import <objc/runtime.h>

static void *choiceViewKey = &choiceViewKey;
@implementation VC (Pay)
- (PayTypeView *)choiceView {
    PayTypeView *choiceView = objc_getAssociatedObject(self, choiceViewKey);
    if (!choiceView) {
         choiceView = [[NSBundle mainBundle] loadNibNamed:@"PayTypeView" owner:nil options:nil].firstObject;
                choiceView.frame = self.view.window.frame;
                [choiceView.alipayTap addTarget:self action:@selector(alipayAction)];
                [choiceView.wechatPayTap addTarget:self action:@selector(wechatAction)];
        objc_setAssociatedObject(self, choiceViewKey, choiceView, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    }
    
    return choiceView;
}
- (void)setChoiceView:(PayTypeView *)choiceView {
     objc_setAssociatedObject(self, choiceViewKey, choiceView, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

@end

2,使用@selector()

#import <objc/runtime.h>

@implementation VC (Pay)
- (PayView *)choiceView {
    PayView *choiceView = (PayView *)objc_getAssociatedObject(self, @selector(choiceView));
    if (!choiceView) {
        choiceView = [[NSBundle mainBundle] loadNibNamed:@"PayView" owner:nil options:nil].firstObject;
        choiceView.frame = self.view.window.frame;
        [choiceView.alipayTap addTarget:self action:@selector(pay)];
        objc_setAssociatedObject(self, @selector(choiceView), choiceView, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    }
    return choiceView;
}
@end
- (void)setChoiceView:(PayView *)choiceView {
    objc_setAssociatedObject(self, @selector(choiceView), choiceView, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

注意:

  • 对于普通的OC对象, 通常采用OBJC_ASSOCIATION_RETAIN_NONATOMIC.
  • 对于NSString等通常采用copy关键字的属性, 通常采用OBJC_ASSOCIATION_COPY_NONATOMIC.
  • 对于枚举等通常采用assign关键字的属性, 通常采用OBJC_ASSOCIATION_ASSIGN.

参考:

在Objective-C的Category中使用属性的懒加载

另外:
\color{#ea4335}{在Category的.m中,写一个类的声明,重写一个同名属性,可以使用VC中的属性,这样也不需要再另外写getter/setter方法。}

vc的.m中

@interface VC () 
@property (copy, nonatomic) NSString * price;
@end

vc的Category的.m中

@interface VC () 
@property (copy, nonatomic) NSString * price;
@end
@implementation VC (Pay)
- (void)payWithPrice:(NSString *)price completion:(PayBlock)completion {
    self.price = price;
}
@end

————————————————

希望后人珍惜时间,少走弯路,享受生活。


VKOOY

上一篇下一篇

猜你喜欢

热点阅读