Skip to content

Instantly share code, notes, and snippets.

@neonichu
Created April 23, 2014 08:41
Show Gist options
  • Save neonichu/11207364 to your computer and use it in GitHub Desktop.
Save neonichu/11207364 to your computer and use it in GitHub Desktop.
NSKeyedArchiver with circular arrays
NSMutableArray* bar = [@[] mutableCopy];
NSArray* foo = @[ bar ];
[bar addObject:foo];
//NSLog(@"%@", foo);
NSString *fileName = [NSString stringWithFormat:@"%@_%@",
[[NSProcessInfo processInfo] globallyUniqueString], @"file.data"];
NSURL* tempfileURL = [NSURL fileURLWithPath:[NSTemporaryDirectory()
stringByAppendingPathComponent:fileName]];
NSMutableData *data = [NSMutableData data];
NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
[foo encodeWithCoder:archiver];
[archiver finishEncoding];
[data writeToURL:tempfileURL atomically:YES];
NSData *readData = [NSData dataWithContentsOfURL:tempfileURL];
NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:readData];
NSArray* moo = [[NSArray alloc] initWithCoder:unarchiver];
[unarchiver finishDecoding];
NSLog(@"%@", moo);
@neonichu
Copy link
Author

This crashes when logging moo with

'NSInvalidArgumentException', reason: '*** -[NSMutableArray count]: method sent to an uninitialized mutable array object'

So I can archive but not unarchive a circular graph?

@neonichu
Copy link
Author

Documentation seems to suggest it should work with NSKeyedArchiver, just not with NSCoder.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment