相信大家有遇到過這種情況,有時候圖省事想把方法寫成+(靜態方法或者叫類方法),但是在類方法里面使用_property
或者self.property
是不允許的,但是往往我們會在類方法里用到公共的屬性,那該如何處理呢?
這里提供一個小技巧,直接上代碼---->
這里先聲明一個類TPProgressModel
,.h
文件中:
@interface TPProgressModel : NSObject
+ (void)setMode:(TPProgressHudMode)mode;
+ (TPProgressHudMode)getMode;
+ (void)setLabel:(UILabel *)label;
+ (UILabel *)getLabel;
+ (void)setCustomView:(UIView *)customView;
+ (UIView *)getCustomView;
+ (void)setAnimationView:(UIView *)animationView;
+ (UIView *)getAnimationView;
+ (void)setPercentView:(UIView *)view;
+ (UIView *)getPercentView;
+ (void)setKeyAnimation:( CAKeyframeAnimation*)key;
+ (CAKeyframeAnimation *)getKey;
@end
.m
文件中:
@implementation TPProgressModel
static TPProgressHudMode _mode = 0;
static UILabel *_label = nil;
static UIView *_customView = nil;
static UIView *_animationView = nil;
static CAKeyframeAnimation *_key = nil;
static UIView *_perView = nil;
+ (void)setMode:(TPProgressHudMode)mode{
_mode = mode;
}
+ (TPProgressHudMode)getMode{
return _mode;
}
+ (void)setLabel:(UILabel *)label{
_label = label;
}
+ (UILabel *)getLabel{
return _label;
}
+ (void)setCustomView:(UIView *)customView{
_customView = customView;
}
+ (UIView *)getCustomView{
return _customView;
}
+ (void)setAnimationView:(UIView *)animationView{
_animationView = animationView;
}
+ (UIView *)getAnimationView{
return _animationView;
}
+ (void)setKeyAnimation:( CAKeyframeAnimation*)key{
_key = key;
}
+ (CAKeyframeAnimation *)getKey{
return _key;
}
+ (void)setPercentView:(UIView *)view{
_perView = view;
}
+ (UIView *)getPercentView{
return _perView;
}
@end
使用方式如下:
在我們需要使用的全局變量或屬性的set
方法里:
- (void)setMode:(TPProgressHudMode)mode{
[TPProgressModel setMode:mode];
}
通過get
使用:
+ (void)showHudInView:(UIView *)view{
dispatch_async(dispatch_get_main_queue(), ^{
[self showView:view indicator:[self indicatorView:view] tag:HudViewTag mode:[TPProgressModel getMode]];
});
}
如此便可以在類方法里面使用全局變量了.
補充
評論中感謝@席萍萍Brook_iOS深圳的提示,發現在UIApplication類中已經有一種方式可以在類方法中調用全局屬性,大概這樣定義:
@property(class,nonatomic,strong) NSString *classProperty;//需要加一個class關鍵字,
并且需要在.m中實現對應的set,get方法
實現如下,Class表示當前類
+ (void)setClassProperty:(NSString *)classProperty{
Class.classProperty = classProperty;
}
+ (NSString *)classProperty{
return Class.classProperty;
}
注意:這種方式用起來有問題,不推薦
如果不清楚后面這種使用方式,第一種估計是最容易想到的方式.
2018-01-22補充:
其實還有種方式,就是利用單例進行保存,但這種方式保存之后如果不進行復位操作,那么后面的模塊可能也會使用之前的屬性,所以也有一定風險.