简体   繁体   English

如何将用户定义的类对象的NSMutableArray存储到iPhone中的文件系统?

[英]How to store NSMutableArray of user defined class objects to file system in iphone?

Can anyone please tell me how to write NSMutableArray of custom class objects to file? 谁能告诉我如何将自定义类对象的NSMutableArray写入文件? below is the code which i am using to write my array "medicationsArray" to file. 下面是我用来将数组“ medicationsArray”写入文件的代码。 medicationsArray contains the objects of below medicationData class medicinesArray包含下方的drugDataData类的对象

@interface medicationData: NSObject { NSString *drName; @interface drugData:NSObject {NSString * drName; NSString *date; NSString *日期; NSString *description; NSString *说明; } @end } @结束

NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *documentDir = [path objectAtIndex:0];
NSString *pathWithFileName;

NSString *pathWithFileName = [NSString stringWithFormat:@"%@/medicationsArray",documentDir];
[medicationsArray writeToFile:pathWithFileName atomically:NO];

by using this code i am not able to create a file. 通过使用此代码,我无法创建文件。 can anyone help me in this, thanks in advance 谁能帮助我,在此先感谢

Instead of constructing the pathWithFileName "manually" you should use the stringByAppendingPathComponent: method instead: 代替“手动”构造pathWithFileName,应使用stringByAppendingPathComponent:方法代替:

NSString *pathWithFileName = [documentDir stringByAppendingPathComponent:@"medicationsArray"];

This will take care of any extra slashes, etc. in the path. 这将照顾路径中的所有多余斜杠等。 This might be the reason your path may be wrong. 这可能是您的路径错误的原因。 I presume that the extra declaration of pathWithFileName in your snippet is just a typo. 我认为您的代码段中的pathWithFileName额外声明只是一个错字。

Thank you for the reply Claus, Now i am able to store the data, i am using NSArchiver and NSUnArchiver. 谢谢克劳斯的答复,现在我能够存储数据,我正在使用NSArchiver和NSUnArchiver。 below is the code please find. 下面是代码,请找到。

NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *documentDir = [path objectAtIndex:0];
NSString *pathWithFileName;

pathWithFileName = [NSString stringWithFormat:@"%@/medicationsArray",documentDir];
NSData *savedData = [NSKeyedArchiver archivedDataWithRootObject:appDelegate.medicationsArray];
[savedData writeToFile:pathWithFileName atomically:YES];

to extract the data 提取数据

if([[NSFileManager defaultManager] fileExistsAtPath:pathWithFileName])
{
    NSData *savedData = [[NSData dataWithContentsOfFile:pathWithFileName] retain];
    appDelegate.medicationsArray = [[NSKeyedUnarchiver unarchiveObjectWithData:savedData] retain];
    [objMedicationDetailsTVController.tableView reloadData];
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM