I have a singleton as follows, which creates an instance of NSDictionary to hold my data. Here is the .h:
@interface FirstLast : NSObject
@property (strong, nonatomic, readonly) NSArray *firstArray;
@property (strong, nonatomic, readonly) NSArray *lastArray;
@property (strong, nonatomic, readonly) NSDictionary *fl;
+ (FirstLast *) firstLast;
- (NSDictionary *) tempDic;
@end
Here is the .m
@implementation FirstLast
@synthesize firstArray = _firstArray;
@synthesize lastArray = _lastArray;
@synthesize fl = _fl;
+ (FirstLast *)firstLast {
static FirstLast *singleton;
static dispatch_once_t once;
dispatch_once(&once, ^{
singleton = [[FirstLast alloc] init];
NSLog(@"FirstLast instantiated");
});
return singleton;
}
- (NSDictionary *) tempDic{
_firstArray = [[NSArray alloc] initWithObjects:@"Bob", @"Joe", @"Sally", @"Sue", nil];
_lastArray = [[NSArray alloc] initWithObjects:@"Jones", @"Johnson", @"Thompson", @"Miller", nil];
_fl = [NSDictionary dictionaryWithObjects:_firstArray
forKeys:_lastArray];
NSLog(@"tempDic just made _fl at this address");
NSLog(@"%p", _fl);
return _fl;
}
@end
All of this works fine. In the view controller I instantiate all this for the first time (works fine too):
NSLog(@"VC is setting up tempDic");
[[WordsClues wordsClues] tempDic];
When I try to gain access to tempDic elsewhere, like this:
NSInteger rIndex = arc4random_uniform(4) + 1;
NSString *fname = [[[FirstLast firstLast].tempDic allValues] objectAtIndex:rIndex];
it works fine, but, when I repeat this process, each time I’m creating a new tempDic. I know this because the NSLog giving the address gives a different answer each time. I really want to access the existing dictionary, which is what I thought my singleton was going to accomplish. Clearly I’m either not accessing tempDic correctly or I misunderstand what the singleton can do for me or I have the tempDic set up wrong. The goal is to get a random value from a single copy of tempDic and not write local copies of tempDic all over the place. Thanks.
Why do you recreate the dictionary in
-tempDicat all?I.e. move the dictionary instantiation code to
initand then justreturn _fl;intempDic.No worries — we’ve all been there [new].
In your FirstLast class, implement the
initmethod as something like:Then change -tempDic to:
I would highly recommend that you read a good intro to Objective-C book. I’m a purist and, thus, would recommend going to the source for the information, but there are lots of books available.
The questions you are asking are more in line with “What is object oriented programming and how does Objective-C work?”.
To answer your question;
FirstLastis a class and the singleton pattern makes sure there is exactly one instance of that class. By moving the creation of the dictionary to theinitmethod — which is called only once and who stores a reference to the created dictionary in an instance variable — you avoid creating multiple dictionary instances.