简体   繁体   English

在目标C中未调用自定义吸气剂

[英]Custom getter not called in Objective C

I'm trying to create a getter for a property - for the time being I'm just using the method to build up an NSMutableObject from static arrays but eventually these will be dynamic config settings. 我正在尝试为属性创建一个吸气剂-暂时,我只是在使用从静态数组构建NSMutableObject的方法,但最终这些将是动态配置设置。 In a previous app and from getter and setters not working objective c I did this: 在以前的应用中,由于getter和setter方法无法正常工作,因此我做到了:

#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;
}

When I get to the line in viewDidLoad where I try to use the 'questions' property, it doesn't use the custom getter (it just assigns bar:FOO to a nil dictionary). 当我到达试图使用'questions'属性的viewDidLoad中的行时,它没有使用自定义的getter(它只是将bar:FOO分配给nil字典)。 What am I missing? 我想念什么?

The reason your custom questions method is not being called through setValue:forKey: is that it is a class method: 您的自定义questions方法未通过setValue:forKey:调用的原因是它是一个类方法:

+ (NSMutableDictionary *)questions is a method defined on the ViewController class, while the property accessor (which setValue:forKey: is looking for) is defined on the instance . + (NSMutableDictionary *)questions是在ViewController类上定义的方法,而属性访问器(正在寻找setValue:forKey:的对象)是在实例上定义的。

To access your custom method as it is currently defined call the class method: 要访问您当前定义的自定义方法,请调用类方法:

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

This may not have the effect you intend, as this value will be shared across all instances of the class. 这可能不会达到您想要的效果,因为此值将在该类的所有实例之间共享。

Try changing the 尝试更改

+ (NSMutableDictionary *)questions

To

- (NSMutableDictionary *)questions

You may also want to change the return type to NSDictionary * to prevent the static variable from being mutated, or return _questions.copy or _questions.mutableCopy 您可能还希望将返回类型更改为NSDictionary *以防止静态变量发生突变,或者返回_questions.copy_questions.mutableCopy

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM