Memory leak using [NSKeyedUnarchiver decodeObjectForKey]

Every time I call this method, I get NSMutableData, and I can’t figure out how to connect it. The data storage score is increased by one after the decoder is allocated and initialized, and I have no idea why. I am stuck with holding 2 at the end of the method, and trying to release it leads to the application crashing.

- (void)readVenueArchiveFile:(NSString *)inFile key:(NSString *)inKey
{
    NSMutableData *theData;
    NSKeyedUnarchiver *decoder;


    theData = [NSData dataWithContentsOfFile:inFile];

    decoder = [[NSKeyedUnarchiver alloc] initForReadingWithData:theData];

    venueIOList = [[decoder decodeObjectForKey:inKey] mutableCopy];

    [decoder finishDecoding];

    [decoder release];
}
+3
source share
5 answers

I would suggest replacing this line:

venueIOList = [[decoder decodeObjectForKey:inKey] mutableCopy];

with:

ListClassName *decodedList = [decoder decodeObjectForKey:inKey];
self.venueIOList = decodedList;

decodedList . ( init). , - readVenueArchiveFile: , ( , decodedList ). , , mutableCopy , ( , ?).

+3

, .

[ .] (1) , . , . , , , , alloc/init.

:

theData = [NSData dataWithContentsOfFile:inFile];

:

theData = [[NSData alloc] initWithContentsOfFile:inFile];

:

[theData release];

, theData . :

- (void)readVenueArchiveFile:(NSString *)inFile key:(NSString *)inKey
{
    NSMutableData *theData;
    NSKeyedUnarchiver *decoder;

    theData = [[NSData alloc] initWithContentsOfFile:inFile];
    decoder = [[NSKeyedUnarchiver alloc] initForReadingWithData:theData];
    ListClassName *decodedList = [decoder decodeObjectForKey:inKey];
    self.venueIOList = decodedList;
    [decoder finishDecoding];
    [decoder release];
    [theData release];

}

.

(1) , . . Apple Memory Management.

+4

, , . , , , , venueIOList - .

: Unarchiver unarchive, -autorelease, -release. , , , .

+2

, , - IMO, " , , " Stepwise.

+1
source

Your code is correct; no memory leak.

theData = [NSData dataWithContentsOfFile:inFile];

equivalently

theData = [[[NSData alloc] initWithContentsOfFile:inFile] autorelease];

At this point, Data has a reference count of 1 (if less, it will be freed). The reference counter will automatically decrease at some point in the future by the pool of autoresists.

decoder = [[NSKeyedUnarchiver alloc] initForReadingWithData:theData];

The decoder object stores a link to Data, which increments the reference count to 2.

After the method returns, the resource pool will reduce this value to 1. If you release Data at the end of this method, the reference counter will become 0, the object will be freed, and your application will crash when you try to use it.

0
source

Source: https://habr.com/ru/post/1697884/


All Articles