4

I am trying out FMDB and it looks like it will work perfectly for me IF I can get my FMResultSet turned into an NSMutableArray.

How would I accomplish this?

Slee
  • 27,498
  • 52
  • 145
  • 243

2 Answers2

13

You could try this.

NSMutableArray *array = [NSMutableArray array];
FMDatabase *database = [FMDatabase databaseWithPath:databasePath];

[database open];

FMResultSet *results = [database executeQuery:@"SELECT * FROM Table"];
while ([results next]) {
    [array addObject:[results resultDictionary]];
}

NSLog(@"%@", array);

[database close];

I am using this in project, and it's working just fine.

Jahm
  • 658
  • 1
  • 12
  • 27
9

The sample code for FMDB illustrates pretty clearly how FMResultSet works. You iterate over the rows in the result set by calling the next method on each iteration. Inside the loop you use the data accessor methods to retrieve the data per column for the current row. If you want to turn this into an array, you have to do this manually. Like this:

NSMutableArray *array = [NSMutableArray array];
FMResultSet *rs = [db executeQuery:@"select * from table"];
while ([rs next]) {
    // Get the column data for this record and put it into a custom Record object
    int col1 = [rs intForColumn:@"col1"];
    int col2 = [rs intForColumn:@"col2"];
    Record *record = [Record recordWithCol1:col1 col2:col2];
    [array addObject:record];
}
[rs close];

As you see, I am assuming that you have built a custom Record class that represents a record in your database table. You could also work with a dictionary, of course.

Ole Begemann
  • 135,006
  • 31
  • 278
  • 256
  • Thanks, that would work but would add to much overhead for my app but good to know none the less – Slee Dec 09 '11 at 19:00