@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.
参考:
另外:
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
网友评论