I’m trying to create a class that inherits NSMutableDictionary. Whenever I initialize an object based on this class, it returns null.
Class:
- (NSMutableDictionary*) init
{
self = [super init];
if (self)
{
self = [[NSUserDefaults standardUserDefaults] objectForKey: MasterKey];
}
return self;
}
Init object:
if (self.masterDict == nil)
{
self.masterDict = [[CardlyMasterDictionary alloc] init];
}
When I debug, I call po [self masterDict] and returns a nil object at 0x0000000. Is there another step I need to take to correctly instantiate an NSMutableDictionary?
dont do this!
(EDIT As @newacct has commented, there are details about the requirements for subclassing NSDictionary in the documentation. However, they still recommend not to do it if possible).
Apple recommend not to subclass the basic nsdict, nsset, nsstring etc classes – they aren’t ‘real’ classes, they are class clusters which means that you don’t actually know which class you have received when you instantiate an nsdictionary.
What you should do is to make a class that has a nsdictionary as a private property – that way you’re not doing anything odd with a dictionary but can’t still wrap its functionality. This is a pretty good principle to follow generally!
It’s also a little unusual to create a new object inside your unit method and point self to it – each time you call alloc/init you are allocating two chunks of memory instead of just one. I would make a class level
PS just realised I didn’t answer your question!
The reason you are getting nil is because you don’t have anything in your user defaults the first time you call this method. This means that your init method will set self to be nil. If this happens you would need to do