@property class

偶然间看到一段代码


@property (nonatomic, class, readonly, nonnull) NSArray * favoritesPlaylist;

应该叫类变量,类属性,类成员还是什么的,具体还是上代码吧,我们先在头文件 写好

@interface User : NSObject
@property (class, nonatomic, assign, readonly) NSInteger userCount;
@property (class, nonatomic, copy) NSUUID *identifier;
+ (void)resetIdentifier;
@end

然后m文件这样写

@implementation User
static NSUUID *_identifier = nil;
static NSInteger _userCount = 0;

get方法

+ (NSUUID *)identifier {
  if (_identifier == nil) {
    _identifier = [[NSUUID alloc] init];
  }
  return _identifier;
}

+ (void)setIdentifier:(NSUUID *)newIdentifier {
  if (newIdentifier != _identifier) {
    _identifier = [newIdentifier copy];
  }
}

+ (NSInteger)userCount {
  return _userCount;
}

假如需要记录创建次数

- (instancetype)init
{
  self = [super init];
  if (self) {
    _userCount += 1;
  }
  return self;
}

如果你的类方法是每次都创建一个实例对象,就没必要写什么lazyloading

+ (void)resetIdentifier {
  _identifier = [[NSUUID alloc] init];
}

然后我们就可以愉快地使用了

User.userCount;
User.identifier;

例子

for (int i = 0; i < 3; i++) {
    self.user = [[User alloc] init];
    NSLog(@"User count: %ld",(long)User.userCount);
    NSLog(@"Identifier = %@",User.identifier);
}

[User resetIdentifier];    
NSLog(@"Identifier = %@",User.identifier);

Swift的写法

public class User : NSObject { 
  public class var userCount: Int { get }
  public class var identifier: UUID!   
  public class func resetIdentifier()
}

学习文章:
https://useyourloaf.com/blog/objective-c-class-properties/

你可能感兴趣的:(@property class)