偶然間看到一段代碼
@property (nonatomic, class, readonly, nonnull) NSArray<NSString *> * 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;
}
假如需要記錄創(chuàng)建次數(shù)
- (instancetype)init
{
self = [super init];
if (self) {
_userCount += 1;
}
return self;
}
如果你的類方法是每次都創(chuàng)建一個實例對象矢否,就沒必要寫什么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/