2

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).

Gazzer
  • 4,524
  • 10
  • 39
  • 49

1 Answers1

3

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.

zoul
  • 102,279
  • 44
  • 260
  • 354
  • `NSNumber` and `NSDate` both work fine in plists. Also don't need `wordDict = nil;` – amattn Mar 27 '11 at 07:59
  • Can I use something similar if I store the result in Database (SQLite) rather than writing to a file? – Gazzer Mar 27 '11 at 08:49
  • 1
    The property list is a string, you can store it almost anywhere. I’m just not sure if it’s the best idea, what are you really trying to do? – zoul Mar 27 '11 at 08:57
  • I have a very big database and I'm doing live search on it. However much I've optimized it, it's not *quite* as fast as I'd like - but acceptable. However, if I make a key for the search that someone has made (which has a LIMIT 20) then I can store this, and subsequent searches will be much faster. I don't want the app to go over 20 megs so I can't do this in advance. (Could you edit your answer and just add how to create the plist) – Gazzer Mar 27 '11 at 17:15
  • Aha. In that case you might ask a new question about query caching or database optimization? Because storing another column with structured string data does not sound optimal. ¶ Creating the plist string is easy, just create a [temporary file](http://stackoverflow.com/questions/215820) using the methods mentioned above and then read the file contents into a string (there’s a special initializer just for that). – zoul Mar 28 '11 at 06:54