如何为Objective-C添加类属性

我们都知道在swift中很容易就能为一个类添加一个类属性,就像这样<code>public static var name:String?</code>,可在OC中我们应该怎么为一个类添加类属性呢?
我们可以在属性的描述词里添加一个class的描述,如下所示

@interface SPCustomType : NSObject
//在这添加了一个class,代表着这是一个类属性
@property (nonatomic,copy,class)NSString *name;
@property (nonatomic,assign,class)NSInteger count;
@end

但是值得注意的是,Xcode并不会为我们自动生成一个对应的类变量,也就是说@property (nonatomic,copy,class)NSString *name;相当于写成这样+ (NSString *)name;+ (void)setName:(NSString *)name;,有一个+号的getter和一个+号setter方法,所以我们需要去实现这2个类方法。

static NSString *_name;
static NSInteger _count;
<code>+</code> (NSString *)name{
    return _name;
}
<code>+</code> (void)setName:(NSString *)name{
    _name = name;
}
<code>+</code> (NSInteger)count{
    return _count;
}
<code>+</code> (void)setCount:(NSInteger)count{
    _count = count;
}
@end

接下来我们就可以用类属性了。例如

NSLog(@"%ld",(long)SPCustomType.count);//打印结果是1
SPCustomType.name = @"testName";
NSLog(@"%@",SPCustomType.name);//打印结果是testName

有的人会有疑问,既然加上class这个描述词之后,仅仅相当于生成了+号getter和setter方法的声明,那为什么我们能通过点语法进行调用呢?
其实点语法并不是去访问成员变量,而是方法的调用。ClassA.test相当于[ClassA test]ClassA.test=@"test"相当于[ClassA setTest:"test"]ClassA既可以是一个对象也可以是一个类.简单测试如下

//声明
@interface SPDotTestClass : NSObject
<code>+</code> (void)sayHello;
<code>+</code> (void)setName:(NSString *)name;
@end
//实现
@implementation SPDotTestClass
<code>+</code> (void)sayHello{
    NSLog(@"sayHello");
}
<code>+</code> (void)setName:(NSString *)name{
    NSLog(@"hello %@",name);
}
@end
//测试代码
SPDotTestClass.sayHello;//此处打印sayHello
SPDotTestClass.name = @"lkk";//此处打印hello lkk

还有更简单的证明,就是我们经常用的[UIApplication sharedApplication];也可以写成IApplication.sharedApplication;当然不建议这么去写。
在回到上面为OC添加类属性上,并不是真正的为一个类添加了类属性,只是看起来好像有了个类属性。添加类属性这个功能应该是为了更好的兼容Swift

    原文作者:lkkwxy
    原文地址: https://www.jianshu.com/p/5fc2c1875bae
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞