Saving Array to Plist file that contains Custom Objects iPhone

前端 未结 5 1294
猫巷女王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:12

    Conforming your XYZ class to the NSCoding protocol is indeed very suitable for what you're trying to do. To do so, add the NSCoding protocol to your class's interface declaration:

    @interface XYZ 
    

    Then, you need implement encodeWithCoder: and initWithCoder: in your implementation. "Encode with coder" means "take your object's current state, and pack it into a generic object called an 'encoder'". "Init with coder" means "given an already-packed encoder object, configure yourself with the data packed into the encoder". In both of these methods, the 'encoder' will be an instance of NSCoder, which has a fairly simple interface for encoding ("packing") and decoding ("unpacking") basic types.

    Here's a sample implementation:

    @implementation XYZ
    - (id)initWithCoder:(NSCoder*)encoder
    {
        self = [self init];
    
        if (self)
        {
            self.myIntProperty = [encoder decodeIntForKey:@"myInt"];
        }
    
        return self;
    }
    
    – (void)encodeWithCoder:(NSCoder*)decoder
    {
        [decoder encodeInt:self.myIntProperty forKey:@"myInt"];
    }
    
    @end
    

提交回复
热议问题