How do I archive an NSArray of NSDictionary (with NSCoding)?
Suppose I am holding data in an array like this
wordList = 开发者_运维百科[[NSMutableArray alloc] init];
while ([rs next]) //Some database return loop
{
wordDict = [[NSMutableDictionary alloc] init];
[wordDict setObject:[NSNumber numberWithInt:[rs intForColumn:@"id"]] forKey:@"id"];
[wordDict setObject:[rs stringForColumn:@"word"] forKey:@"word"];
[wordList addObject: wordDict];
[wordDict release];
wordDict = nil;
}
But I want to store this result (i.e. wordList) in SQLite for later use - I guess using NSCoding
. How would I do that?
(Feel free to point out any errors in how stuff is being alloc'ed if there are problems there).
If you don’t insist on serialization using NSCoding
, there’s a writeToFile:atomically:
method both on NSArray
and NSDictionary
. This will serialize your object into a property list (*.plist
). The only catch is that all the objects in the “tree” to be serialized must be NSString
, NSData
, NSArray
, or NSDictionary
(see the documentation). I’m not sure how NSNumber
fits in, but with a bit of luck it will be serialized and deserialized too. The inverse method that will turn the file back into a dictionary or an array is called initWithContentsOfFile:
.
As for your code, I would just use the [NSMutableDictionary dictionary]
convenience method that gets you an autoreleased dictionary. It’s shorter than the usual alloc
& init
and you save one line for the explicit release.
精彩评论