@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關(guān)鍵字的屬性, 通常采用OBJC_ASSOCIATION_COPY_NONATOMIC.
- 對于枚舉等通常采用assign關(guān)鍵字的屬性, 通常采用OBJC_ASSOCIATION_ASSIGN.
參考:
另外:
在Category的.m中森瘪,寫一個(gè)類的聲明匹耕,重寫一個(gè)同名屬性,可以使用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