Pergunta

Every time an event is triggered, my app records its date:

NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *filename = [path stringByAppendingPathComponent:@"dates.dat"];

if (![[NSFileManager defaultManager] fileExistsAtPath:filename]) {
    [[NSFileManager defaultManager] createFileAtPath:filename
                                            contents:nil
                                          attributes:nil];
}

NSFileHandle *wHandle = [NSFileHandle fileHandleForWritingAtPath:filename];
[wHandle seekToEndOfFile];

NSData *data = [NSKeyedArchiver archivedDataWithRootObject:[NSDate date]];

[wHandle writeData:data];

[wHandle closeFile];

I successfully record the events' dates. But now I am having troubles in reading them back. I tried this but the app crashes:

NSData *restore = [NSData dataWithContentsOfFile:filename];
NSArray *date1 = [NSKeyedUnarchiver unarchiveObjectWithData:restore]; // crash here!

I notice that it takes 223 bytes for each NSDate write but that is not officially mentioned. So I am afraid that using 223 bytes as length to parse the file "dates.dat" would cause problems later.

Do you have any ideas to read dates.dat into an NSArray so I can proceed its values?

Thanks in advance

Foi útil?

Solução

Don't store the dates as arbitrary blocks of data in a file (because you're correct, you shouldn't rely on the number of bytes used for each date).

As a minimum, use a separator character (like a carriage return) so you know which data belongs to each different date. Then you need to parse the file and read in only the appropriate data before you try to unarchive it.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top