也许这很明显,但我不知道如何在Objective-C中声明类属性。
我需要缓存每个类的字典,不知道如何把它放在类。
也许这很明显,但我不知道如何在Objective-C中声明类属性。
我需要缓存每个类的字典,不知道如何把它放在类。
当前回答
如果您有许多类级属性,那么单例模式可能是合适的。 就像这样:
// Foo.h
@interface Foo
+ (Foo *)singleton;
@property 1 ...
@property 2 ...
@property 3 ...
@end
And
// Foo.m
#import "Foo.h"
@implementation Foo
static Foo *_singleton = nil;
+ (Foo *)singleton {
if (_singleton == nil) _singleton = [[Foo alloc] init];
return _singleton;
}
@synthesize property1;
@synthesize property2;
@synthesise property3;
@end
现在像这样访问你的类级属性:
[Foo singleton].property1 = value;
value = [Foo singleton].property2;
其他回答
如果您有许多类级属性,那么单例模式可能是合适的。 就像这样:
// Foo.h
@interface Foo
+ (Foo *)singleton;
@property 1 ...
@property 2 ...
@property 3 ...
@end
And
// Foo.m
#import "Foo.h"
@implementation Foo
static Foo *_singleton = nil;
+ (Foo *)singleton {
if (_singleton == nil) _singleton = [[Foo alloc] init];
return _singleton;
}
@synthesize property1;
@synthesize property2;
@synthesise property3;
@end
现在像这样访问你的类级属性:
[Foo singleton].property1 = value;
value = [Foo singleton].property2;
从Xcode 8开始,你可以像Berbie回答的那样使用class属性。
但是,在实现中,您需要使用静态变量代替iVar为类属性定义类getter和setter。
Sample.h
@interface Sample: NSObject
@property (class, retain) Sample *sharedSample;
@end
Sample.m
@implementation Sample
static Sample *_sharedSample;
+ ( Sample *)sharedSample {
if (_sharedSample==nil) {
[Sample setSharedSample:_sharedSample];
}
return _sharedSample;
}
+ (void)setSharedSample:(Sample *)sample {
_sharedSample = [[Sample alloc]init];
}
@end
这里有一个线程安全的方法:
// Foo.h
@interface Foo {
}
+(NSDictionary*) dictionary;
// Foo.m
+(NSDictionary*) dictionary
{
static NSDictionary* fooDict = nil;
static dispatch_once_t oncePredicate;
dispatch_once(&oncePredicate, ^{
// create dict
});
return fooDict;
}
这些编辑确保只创建一次fooDict。
来自Apple文档:“dispatch_once—在应用程序的生命周期中执行一次且仅执行一次块对象。”
你可以在Swift类中创建一个静态变量,然后从任何Objective-C类中调用它。
正如在WWDC 2016/XCode 8上看到的那样(LLVM会话@5:05的新内容)。类属性可以如下声明
@interface MyType : NSObject
@property (class) NSString *someString;
@end
NSLog(@"format string %@", MyType.someString);
注意,从不合成类属性
@implementation
static NSString * _someString;
+ (NSString *)someString { return _someString; }
+ (void)setSomeString:(NSString *)newString { _someString = newString; }
@end