In my non-ARC iOS project, I have a method that returns archived data:
- (NSData*) archivedData {
NSMutableData* data = [[NSMutableData alloc] init];
NSKeyedArchiver* archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
// Encode the fields that must be archived:
[archiver encodeObject:... forKey:...];
...
[archiver finishEncoding];
[archiver release];
return [data autorelease];
Since initForWritingWithMutableData:
is deprecated, I modified the implementation:
- (NSData*) archivedData {
NSKeyedArchiver* archiver = [[NSKeyedArchiver alloc] initRequiringSecureCoding:YES];
// Encode the fields that must be archived:
[archiver encodeObject:... forKey:...];
...
[archiver finishEncoding];
NSData* data = [archiver encodedData];
[archiver release];
return data;
At first, I called autorelease
on the encoded NSData
object before returning it but that resulted in a bad memory access (EXC_BAD_ACCESS
). Everything seems to work fine without autorelease
.
I am now confused. Since I release the archiver before returning the data, I thought autorelease
would protect the NSData
object, deallocating it not before it is processed by the calling method. I worried that the NSData
object might be deallocated right after the archiver is released without the autorelease
call. Somehow, the opposite happens when I run the code.
Could anybody please shed some light on this behavior? Also, if I'm doing something wrong, I'd like to know how to fix the code.
I'm aware of the static method archivedDataWithRootObject:requiringSecureCoding:error:
but I can't easily use it because I don't have a root object as I encode objects individually. Using a root object would break compatibility for existing users of the app (if I understand it correctly).