Encode NSArray or NSDictionary using NSCoder

前端 未结 3 1236
花落未央
花落未央 2020-12-09 10:09

I was wondering whether or not it is possible to use the NSCoder method:

- (void)encodeObject:(id)objv forKey:(NSString *)key

to encode eit

相关标签:
3条回答
  • 2020-12-09 10:49

    NSKeyedArchiver/Unarchiver should encode and decode NSArrays and NSDictionaries with no problem. If your packet class you've created implements the NSCoding protocol, you need to explicitly call [encodeObject:myNsArrayforKey:@"stringsArray"] in your -encodeWithCoder: method (assuming that myNsArray is the name of the instance variable in your packet object you want to encode). But then the archiver and NSArray should take care of the rest of it. If you're doing this, it would be helpful to hear more about the layout of your classes and who's calling who when encoding/decoding.

    0 讨论(0)
  • 2020-12-09 10:54

    What kind of objects are you storing in the array? Make sure that all objects stored in the array implement the NSCoding protocol.

    0 讨论(0)
  • 2020-12-09 11:09

    If the array or dictionary is the root object you should do

    NSData * encodedData = [NSKeyedArchiver archivedDataWithRootObject:someArray];
    

    or

    BOOL success = [NSKeyedArchiver archiveRootObject:someArray toFile:filePath];
    

    If it is an instance variable of a custom class, in the -encodeWithCoder: method should do

    [coder encodeObject:someArray forKey:@"someArray"];
    

    and then in the -initWithCoder: method

    someArray = [[coder decodeObjectForKey:@"someArray"] retain];
    
    0 讨论(0)
提交回复
热议问题