문제

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

도움이 되었습니까?

해결책

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top