Saving Array to Plist file that contains Custom Objects iPhone

前端 未结 5 1295
猫巷女王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条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-02-04 23:16

    There is a very good tutorial on the Ray Wenderlich's blog which explains how to work with the NSCoding.

    Simply you just have to implement the *-(void)encodeWithCoder:(NSCoder )encode and *-(id)initWithCoder:(NSCoder )decoder methods in your object that respects the NSCoding protocol like that:

    // Header
    @interface AnObject: NSObject 
    
    // Implementation
    - (void) encodeWithCoder:(NSCoder *)encoder {
        [encoder encodeObject:ivar1 forKey:@"ivar1"];
        [encoder encodeFloat:ivar2 forKey:@"ivar2"];
    }
    
    - (id)initWithCoder:(NSCoder *)decoder {
        self = [super initWithCoder:coder];
        ivar1 = [[coder decodeObjectForKey:@"ivar1"] retain];
        ivar2 = [[coder decodeObjectForKey:@"ivar2"] retain];
        return self;
    }
    

    You can also check the official documentation here.

提交回复
热议问题