目标C

时间:2015-09-19 21:52:51

标签: objective-c

我正在尝试为属性创建一个getter - 暂时我只是使用该方法从静态数组构建NSMutableObject,但最终这些将是动态配置设置。在之前的应用中,getter and setters not working objective c我做了这个:

#import "ViewController.h"

@interface ViewController ()

@property (nonatomic) NSMutableDictionary *questions;

@end

@implementation ViewController

- (void)viewDidLoad {

    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    [[self questions] setValue:@"FOO" forKey:@"bar"];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

+ (NSMutableDictionary *)questions
{
    static NSMutableDictionary *_questions;
    if (_questions== nil)
    {
        NSArray *genders = @[@"male", @"female"];
        NSArray *ages = @[@"<10", @">60", @"Other"];
        _questions = [[NSMutableDictionary alloc] init];
        [_questions setValue:genders forKey:@"gender"];
        [_questions setValue:ages forKey:@"age"];

    }

    return _questions;
}

当我到达viewDidLoad中我尝试使用'questions'属性的行时,它不使用自定义getter(它只是将bar:FOO指定为nil字典)。我错过了什么?

1 个答案:

答案 0 :(得分:1)

您的自定义questions方法未通过setValue:forKey:调用的原因是它是一种类方法:

+ (NSMutableDictionary *)questions是在ViewController类上定义的方法,而属性访问器(setValue:forKey:正在查找)是在实例上定义的。 / p>

要访问当前定义的自定义方法,请调用类方法:

[[[self class] questions] setValue:@"FOO" forKey:@"bar"];

这可能没有你想要的效果,因为这个值将在所有类的实例中共享。