In this example my NSDictionary initializes with 0 key/value pairs, as shown in my debugger. It will initialize properly when I do the exact same thing in my ViewController but I would much prefer to stick to MVC design and have the NSDictionary in my model.
ShakespeareViewController.h
#import <UIKit/UIKit.h>
@interface ShakespeareViewController : UIViewController
@property (weak, nonatomic) IBOutlet UILabel *sonnetDisplay;
@end
ShakespeareViewController.m
#import "ShakespeareViewController.h"
#import "ShakespeareModel.h"
@interface ShakespeareViewController ()
@property (nonatomic, strong) ShakespeareModel *sonnet;
@end
@implementation ShakespeareViewController
@synthesize sonnetDisplay = _sonnetDisplay;
@synthesize sonnet = _sonnet;
- (IBAction)sonnetButton:(UIButton *)sender
{
self.sonnetDisplay.text = [self.sonnet grabSonnet:@"19"];
}
@end
ShakespeareModel.h
#import <Foundation/Foundation.h>
@interface ShakespeareModel : NSObject
-(NSString *)grabSonnet:(NSString *)atNumber;
@end
ShakespeareModel.m
#import "ShakespeareModel.h"
@interface ShakespeareModel()
@property (nonatomic, strong) NSDictionary *sonnets;
@end
@implementation ShakespeareModel
@synthesize sonnets = _sonnets;
-(NSDictionary *)sonnets
{
if (!_sonnets)
{
_sonnets = [[NSDictionary alloc] initWithObjectsAndKeys:@"19", @"19", nil];
}
return _sonnets;
}
-(NSString *)grabSonnet:(NSString *)atNumber
{
NSString *chosenSonnet = [self.sonnets objectForKey:@"19"];
return chosenSonnet;
}
@end
Any ideas on what I am doing wrong are greatly appreciated. I can’t see why this wouldn’t initialize with the object 19 at key value 19.
I don’t see any place where you set the view controller’s
sonnetproperty to an instance ofShakespeareModel— so when you callgrabSonnet:you’re sending a message tonil(and thus getting nothing back.You should put
self.sonnet = [[ShakespeareModel alloc] init]in your view controller some time before you callgrabSonnet:… probably in the initializer or in-viewDidLoad.