This code does not give any error but it's not creating the "plist" file nor reading from it.
I wrote a code that specifies the direct path to the folder and it creates and writes to the file although it cannot read from it.
[NSKeyedArchiver archiveRootObject:employees toFile:@"/Users/Documents/employees.plist"];
This code below could Not write nor read the file.
And I followed it line by line to the online instructions.
I copied the exact Employee.h
and Employee.m
file and no error there either.
Thank you for your help.
#import <Foundation/Foundation.h>
#import "Employee.h"
NSString* getPropertyListPath() {
NSURL *documentDir = [[NSFileManager defaultManager]
URLForDirectory:NSDocumentationDirectory
inDomain:NSUserDomainMask
appropriateForURL:nil
create:NO
error:nil];
NSURL *plist = [documentDir URLByAppendingPathComponent:@"EmployeeFile.plist"];
return plist.path;
}
void createAndArchiveObjects (NSString *filePath) {
NSLog(@"Creating objects manually");
Employee *john = [[Employee alloc] init];
[john setFirstName:@"A"];
[john setLastName:@"J"];
[john setEmployeeNumber:12345];
[john setHireDate:[NSDate date]];
NSMutableArray *employees = [[NSMutableArray alloc] init];
[employees addObject:john];
[NSKeyedArchiver archiveRootObject:employees toFile:filePath];
NSLog(@"Objects created and archived");
}
void unarchiveSavedObjects(NSString *filePath) {
NSMutableArray *employees = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];
for (Employee *e in employees) {
NSLog(@"The unarchived, reconstituted object is %@", e);
}
}
int main(int argc, const char * argv[])
{
@autoreleasepool {
NSString *path = getPropertyListPath();
if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {
unarchiveSavedObjects(path);
} else {
createAndArchiveObjects(path);
}
}
return 0;
}
The NSLog
displays:
Creating objects manually
Objects created and archived
But no file is created.
You are using NSDocumentationDirectory instead of NSDocumentDirectory.
Use.,
NSURL *documentDir = [[NSFileManager defaultManager]
URLForDirectory:NSDocumentDirectory
inDomain:NSUserDomainMask
appropriateForURL:nil
create:NO
error:nil];