gpt4 book ai didi

ios - NSDocumentDirectory - 写入和读取文件

转载 作者:行者123 更新时间:2023-11-29 04:07:14 26 4
gpt4 key购买 nike

这是用于将 UITextFields 的内容写入文件的代码(姓名、地址、联系人号码、电子邮件)。

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)

最佳答案

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

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

编辑

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

关于ios - NSDocumentDirectory - 写入和读取文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14999980/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com