[英]Objective C singleton class members
这适用于Mac OS X应用。 我已经创建了一个单例类,但是不确定如何添加类成员(不确定这是否是正确的术语)。 我在Property 'chordDictionary' not found on object of type '__strong id'
错误Property 'chordDictionary' not found on object of type '__strong id'
,我不确定为什么。 我想创建一个NSDictionary,可以通过此类访问。 这是我的代码:
#import "ChordType.h"
@interface ChordType()
@property NSDictionary *chordDictionary;
@end
@implementation ChordType
+ (instancetype)sharedChordData {
static id sharedInstance = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedInstance = [[self alloc] init];
sharedInstance.chordDictionary = @{@"" : @"047", @"m" : @"037", @"dim" : @"036", @"aug" : @"048",}; //error is on this line
});
return sharedInstance;
}
@end
声明sharedInstance
作为ChordType *
,而不是id
或拨打setChordDictionary:
方法,而不是使用属性语法。 您不能对id
类型的变量使用属性语法。
要么:
static ChordType *sharedInstance = nil;
要么:
[sharedInstance setChordDictionary:@{@"" : @"047", @"m" : @"037", @"dim" : @"036", @"aug" : @"048"}];
将它们添加到您的ChordType类的头文件中
@property NSDictionary *chordDictionary;
+ (ChordType *)sharedChordData;
然后用这个修改你的代码
+ (ChordType *)sharedChordData {
static id sharedInstance = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedInstance = [[self alloc] init];
sharedInstance.chordDictionary = @{@"" : @"047", @"m" : @"037", @"dim" : @"036", @"aug" : @"048",}; //error is on this line
});
return sharedInstance;
}
然后,您可以访问类似的属性,
[ChordType sharedChordData].chordDictionary = @{@"" : @"047", @"m" : @"037", @"dim" : @"036", @"aug" : @"048"};
这样,您的访问chordDictionary通过其sharedInstance是shareChordData sharedChordData公共财产基本上是可以通过类成员访问的静态方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.