0

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);
    }
}

但它无法读取任何内容。它一直在日志中打印 null 。

File Names: UserDetails
(null)
(null)
4

2 回答 2

1

阅读时忘记添加额外的“路径”

NSString *documentsPath =  [[paths objectAtIndex:0] stringByAppendingPathComponent:@"UserDetails"];

编辑

然后,提供dataWithContentsOfFile:的完整路径。Enumerate 只会给你文件名

于 2013-02-21T10:39:01.560 回答
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];
于 2013-02-21T10:44:08.980 回答