简体   繁体   中英

NSDocumentDirectory - write to & read from file

This is the code used to write to a file from contents of 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);

and this one to read from file.

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

But it is failing to read anything. All time it prints null in logs.

File Names: UserDetails
(null)
(null)

You forget to add extra 'Path' when reading

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

Edit

Then, provide full path to dataWithContentsOfFile: . Enumerate will give you the name of file only

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];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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