Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
474 views
in Technique[技术] by (71.8m points)

iphone - Encode NSArray or NSDictionary using NSCoder

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

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

to encode either an instance of NSArray or NSDictionary. If not how do you go about encoding them? I am trying to use NSKeyedArchived / NSKeyedUnarchiver to send data between phones using GameKit. I tried it and cannot seem to retrieve the string I stored in my array. The packet class I made comes through along with the packet type integer, but not the data in the array it seems.

Thanks in advance!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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];

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...