[iOS]开发小技巧-在+方法里使用全局变量

[iOS]开发小技巧-在+方法里使用全局变量_第1张图片

相信大家有遇到过这种情况,有时候图省事想把方法写成+(静态方法或者叫类方法),但是在类方法里面使用_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补充:
其实还有种方式,就是利用单例进行保存,但这种方式保存之后如果不进行复位操作,那么后面的模块可能也会使用之前的属性,所以也有一定风险.

你可能感兴趣的:([iOS]开发小技巧-在+方法里使用全局变量)