I’ve created an object called ‘DateTracker’ which conforms to NSCoding, so it contains encodeWithCoder and initWithCoder methods. When I initialise it, I call the following:
DateTracker *currentTracker = [[DateTracker alloc] initFromFile];
The initFromFile method looks like this:
- (id)initFromFile {
NSString *filePath = [self dataFilePath];
if ([[NSFileManager defaultManager] attributesOfFileSystemForPath:filePath error:NULL]) {
NSData *data = [[NSMutableData alloc] initWithContentsOfFile:filePath];
NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
self = [unarchiver decodeObjectForKey:kDateDataKey];
[unarchiver finishDecoding];
[unarchiver release];
[data release];
}
return self;
}
However when I try to call
[currentTracker release];
my app crashes.
When I run the app with performance tools to check for memory leaks, it complains that I’m not releasing this object.
Any ideas what I’m doing wrong?
This line:
is going to give you problems.
What you’re doing is to allocate a DateTracker object (
[DateTracker alloc]), then create a new DateTracker object (by-decodeObjectForKey:) and make the “self” pointer refer to the new object. There are two problems with that:I would say the approach of having an object replace itself is a bit suspect. Perhaps you would do better to move the
filePathvariable outside of theDateTrackerobject, and unarchive it by something like:where
unarchiveFromFile:is a class method that does essentially whatinitFromFiledid, without messing withself: