适用于Mac OS X应用。我创建了一个单例类,但我不确定如何添加类成员(不确定这是否是正确的术语)。我收到错误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
答案 0 :(得分:3)
将sharedInstance
声明为ChordType *
而不是id
,或调用setChordDictionary:
方法而不是使用属性语法。您不能对id
类型的变量使用属性语法。
或者:
static ChordType *sharedInstance = nil;
或:
[sharedInstance setChordDictionary:@{@"" : @"047", @"m" : @"037", @"dim" : @"036", @"aug" : @"048"}];
答案 1 :(得分:0)
在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"};
通过这种方式,您通过 shareChordData sharedChordData的sharedInstance访问 chordDictionary 作为公共属性基本上是一个可以通过类成员访问的静态方法。