Save / Write NSMutableArray of objects to disk?

后端 未结 2 771
温柔的废话
温柔的废话 2021-01-12 16:42

Initially I thought this was going to work, but now I understand it won\'t because artistCollection is an NSMutableArray of \"Artist\" objects.

@interface Ar         


        
相关标签:
2条回答
  • 2021-01-12 17:29

    writeToFile:atomically: in Cocoa's collection classes only works for property lists, i.e. only for collections that contain standard objects like NSString, NSNumber, other collections, etc.

    To elaborate on jdelStrother's answer, you can archive collections using NSKeyedArchiver if all objects the collection contains can archive themselves. To implement this for your custom class, make it conform to the NSCoding protocol:

    @interface Artist : NSObject <NSCoding> {
        NSString *firName;
        NSString *surName;
    }
    
    @end
    
    
    @implementation Artist
    
    static NSString *FirstNameArchiveKey = @"firstName";
    static NSString *LastNameArchiveKey = @"lastName";
    
    - (id)initWithCoder:(NSCoder *)decoder {
        self = [super init];
        if (self != nil) {
            firName = [[decoder decodeObjectForKey:FirstNameArchiveKey] retain];
            surName = [[decoder decodeObjectForKey:LastNameArchiveKey] retain];
        }
        return self;
    }   
    
    - (void)encodeWithCoder:(NSCoder *)encoder {
        [encoder encodeObject:firName forKey:FirstNameArchiveKey];
        [encoder encodeObject:surName forKey:LastNameArchiveKey];
    }
    
    @end
    

    With this, you can encode the collection:

    NSData* artistData = [NSKeyedArchiver archivedDataWithRootObject:artistCollection];
    [artistData writeToFile: @"/Users/Fgx/Desktop/stuff" atomically:YES];
    
    0 讨论(0)
  • 2021-01-12 17:31

    Take a look at NSKeyedArchiver. Briefly :

    NSData* artistData = [NSKeyedArchiver archivedDataWithRootObject:artistCollection];
    [artistData writeToFile: @"/Users/Fgx/Desktop/stuff" atomically:YES];
    

    You'll need to implement encodeWithCoder: on your Artist class - see Apple's docs

    Unarchiving (see NSKeyedUnarchiver) is left as an exercise for the reader :)

    0 讨论(0)
提交回复
热议问题