Saving Array to Plist file that contains Custom Objects iPhone

前端 未结 5 1291
猫巷女王i
猫巷女王i 2021-02-04 22:39

I have a class called XYZ inheriting from NSObject and an array which contains objects of XYZ. I need to write this array to a plist file on to documents directory. After trying

5条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-02-04 23:25

    After implementing encodeWithCoder: and initWithCoder: for the custom class here is how to write and read:

    Write:

    NSError  *error;
    NSData* archiveData = [NSKeyedArchiver archivedDataWithRootObject:yourClassInstance];
    [archiveData writeToFile:filePath options:NSDataWritingAtomic error:&error];
    

    Read:

    NSData *archiveData = [NSData dataWithContentsOfFile:filePath];
    YourClass *yourClassInstance = (NSArray*)[NSKeyedUnarchiver unarchiveObjectWithData:archiveData];
    

提交回复
热议问题