NSDocumentDirectory - 写入&从文件中读取

时间:2013-02-21 10:31:36

标签: ios objective-c nsdocumentdirectory

这是用于从UITextFields(name,addr,contactNumber,email)的内容写入文件的代码。

NSDictionary *userDict = [NSDictionary dictionaryWithObjectsAndKeys:
                          self.name.text, @"UserName"
                          ,self.address.text, @"UserAddress"
                          ,self.contactNumber.text, @"UserContactNumber"
                          ,self.email.text, @"UserEmail"
                          , nil];
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:@"UserDetails"];
BOOL writtenToFile = [userDict writeToFile:fullPath atomically:YES];
NSLog(@"writtenToFile: %d",writtenToFile);

这一个从文件中读取。

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0];
NSDirectoryEnumerator *directoryEnumerator = [[NSFileManager defaultManager] enumeratorAtPath:documentsPath];
for (NSString *path in directoryEnumerator)
{
    NSLog(@"File Names: %@", path);
    if ([path isEqualToString:@"UserDetails"]) {
        NSData *data = [NSData dataWithContentsOfFile:path];
        NSLog(@"%@",data);
        NSDictionary *userDict = [[NSDictionary alloc] initWithContentsOfFile:path];
        NSLog(@"%@",userDict);
    }
}

但它没有读任何东西。它一直在日志中打印为空。

File Names: UserDetails
(null)
(null)

2 个答案:

答案 0 :(得分:1)

在阅读

时,您忘记添加额外的'路径'
NSString *documentsPath =  [[paths objectAtIndex:0] stringByAppendingPathComponent:@"UserDetails"];

修改

然后,提供 dataWithContentsOfFile:的完整路径。枚举将为您提供仅文件的名称

答案 1 :(得分:0)

NSString *path = [[[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject] path];
//You'll need an additional '/'
NSString *fullPath = [path stringByAppendingFormat:@"/UserDetails.plist"];
BOOL writtenToFile = [userDict writeToFile:fullPath atomically:YES];