Saving Array to Plist file that contains Custom Objects iPhone

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

    It's pretty straight forward. For given class Foo:

    #import 
    
    @interface Foo : NSObject  {
        NSArray* bar_;
        NSUInteger baz_;
    }
    
    @property (nonatomic, retain) NSArray *bar;
    @property (nonatomic, assign) NSUInteger baz;
    
    @end
    

    All you have to do to conform to the NSCoding protocol is to implement the initWithCoder: and decodeWithCoder messages:

    #import "Foo.h"
    
    @implementation Foo
    @synthesize bar = bar_;
    @synthesize baz = baz_;
    
    #pragma mark - NSCoding
    
    - (void)encodeWithCoder:(NSCoder *)encoder  {
        [encoder encodeObject:self.bar forKey:@"bar"];
        [encoder encodeInteger:self.baz forKey:@"baz"];
    }
    
    - (id)initWithCoder:(NSCoder *)decoder  {
        if ((self = [super init])) {
            self.bar = [decoder decodeObjectForKey:@"bar"];
            self.baz = [decoder decodeIntegerForKey:@"baz"];
        }
        return self;
    }
    
    - (void) dealloc {
    
        [bar_ release];
        [super dealloc];    
    }
    
    @end
    

提交回复
热议问题