У меня есть множество классов, которые используют различные классы коллекций NSDictionary / NSArray в качестве ivars, но часто я сталкиваюсь с проблемой освобождения моего класса коллекции до выпуска содержащего класса.
Похоже, это происходит в основном с классами коллекций, а не с другим классом модели (т. Е. Классами, которые я либо создал отдельно, либо с другими классами NS *, не относящимися к коллекции).
Вот два варианта, которые я сделал и видел, что другие люди делают:
@implementation ClassX
// myDictionary declared as a property in the .h file as this:
// @property (nonatomic, retain) NSMutableDictionary *myDictionary;
@synthesize myDictionary;
- (id)int
{
if (self = [super init])
{
// Option 1:
// If I don't instantiate and assign with 'self',
// myDictionary ivar will not be available
// at times in doSomething.
myDictionary = [NSMutableDictionary dictionary];
// Option 2:
// Doing this, however will keep the dictionary around.
// because I have invoked an extra retain on the dictionary
self.myDictionary = [NSMutableDictionary dictionary];
// Which one is more correct?
}
return self;
}
- (void)doSomething
{
// this will give the error about trying to invoke
// a method on an already released instance
[myDictionary objectForKey:@"myKey"];
}
- (void)dealloc
{
// If I did self.myDictionary in 'init', I then
// need to do this:
[myDictionary release];
[super dealloc];
}
@end
Итак, какой подход является более правильным способом хранения экземпляра NSDictionary внутри класса?