Reputation: 469
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. In a previous app and from getter and setters not working objective c I did this:
#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). What am I missing?
Upvotes: 1
Views: 406
Reputation: 3025
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
Upvotes: 1
Reputation: 21244
The reason your custom questions
method is not being called through setValue:forKey:
is that it is a class method:
+ (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.
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.
Upvotes: 1