DavidNg
DavidNg

Reputation: 2836

Reading from SQLite in Xcode iOS SDK

I have program with a table in SQLite with about 100 rows and 6 colunms of text (not more than hundred of characters). Each time click a button, the program will display in the view a contents of a row in the table.

My question is that should I copy the content of whole table into an array and then reading from array each time user clicks button or I access the table in database each time the user click the button? Which one is more efficient?

Upvotes: 1

Views: 492

Answers (3)

Rob
Rob

Reputation: 438232

It all depends, but retrieving from the database as you need data (rather than storing the whole thing in an array) would generally be most efficient use of memory, which is a pretty precious resource. My most extravagant use of memory would be to store an array of table unique identifiers (i.e. a list of primary keys, returned in the correct order), that way I'm not scanning through the database every time, but my unique identifiers are always numeric, so it doesn't use up too much memory. So, for something of this size, I generally:

  • open the database;
  • load an array of solely the table's unique identifiers (which were returned in the right order for my tableview using the SQL ORDER BY clause);
  • as table cells are built, I'll go back to the database and get the few fields I need for that one row corresponding to the unique identifier that I've kept track of for that one table row;
  • when I go to the details view, I'll again get that one row from the database; and
  • when I'm all done, I'll close the database

This yields good performance while not imposing too much of a drain on memory. If the table was different (much larger or much smaller) I might suggest different approaches, but this seems reasonable to me given your description of your data.

Upvotes: 2

wackytacky99
wackytacky99

Reputation: 614

100 row and 6 columns is not a lot of data. iOS is capable of handling larger data than that and very efficiently. So don't worry about creating a new array. Reading from the database should work just fine.

Upvotes: 0

pithhelmet
pithhelmet

Reputation: 2292

for me - it was much easier to re-read the database for each view load, and drop the contents when done.

the overhead of keeping the contents in memory was just too much to offset the quick read of a small dataset.

Upvotes: 0

Related Questions