この度のAPI変更により、Objective-Cでもクラス変数が宣言できるようになりました🎉
OS X 10.12 and iOS 10 Release Notes Cocoa Foundation Framework
Use of class properties, in both Swift as well as Objective-C, latter using the new "@property (class)" declaration.
使い方
宣言
宣言する際はプロパティの属性にclassを指定します。
Pokedex.h
# import <UIKit/UIKit.h>
@interface Pokedex : NSObject
@property (class, nonnull) UIColor *defaultColor;
@end
実装
実装の際には注意が必要です。
クラスプロパティにはアクセサメソッドが自動では生成されません。
よって自前で定義するかもしくは@dynamicを使って、動的に生成する必要があります。
Pokedex.m
# import "Pokedex.h"
static UIColor *_defaultColor = nil;
@implementation Pokedex
+ (UIColor *)defaultColor {
if (!_defaultColor) {
_defaultColor = UIColor.redColor;
}
return _defaultColor;
}
+ (void)setDefaultColor:(UIColor *)defaultColor {
_defaultColor = defaultColor;
}
@end
呼び出し
ViewController.m
# import "ViewController.h"
# import "Pokedex.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
NSLog(@"Pokedex Color: %@", Pokedex.defaultColor);
}
@end
結果
2016-07-23 22:56:04.415 ClassProperty[8600:324023] Pokedex Color: UIExtendedSRGBColorSpace 1 0 0 1
Swiftからの呼び出し
ViewController.swift
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
print("Pokedex Color: \(Pokedex.defaultColor)")
}
}
結果
Pokedex Color: UIExtendedSRGBColorSpace 1 0 0 1
その他
readonlyにすることも可能です。
Pokedex.h
# import <UIKit/UIKit.h>
@interface Pokedex : NSObject
@property (class, nonnull, readonly) UIColor *defaultColor;
@end
Pokedex.m
# import "Pokedex.h"
@implementation Pokedex
+ (UIColor *)defaultColor {
return UIColor.redColor;
}
@end
おわりに
昨年のLightWeightGenericsといい、
Swiftの影響でObjective-Cも便利になってきてますね!
参考
OS X 10.12 and iOS 10 Release Notes Cocoa Foundation Framework
Objective-C Class Properties