iOS: filter SQLite query / check entry against former entries
Okay, so I'm doing a search in a SQLite database for all entries in the row called Artists... But I don't want the same artist to appear twice...
-(NSArray *)findAllArtists
{
NSMutableArray *returnArray = [[[NSMutableArray alloc] init] autorelease];
NSString *query = @"SELECT * FROM Painting";
sqlite3_stmt *statement;
if (sqlite3_prepare_v2(database, [query UTF8String], -1, &statement, nil)
== SQLITE_OK)
{
while (sqlite3_step(statement) == SQLITE_ROW)
{
char *uniqueIdChars = (char *) sqlite3_column_text(statement, 0);
char *artistChars = (char *) sqlite3_column_text(statement, 1);
NSString *uniqueId = [[NSString alloc] initWithUTF8String:uniqueIdChars];
NSString *artist = [[NSString alloc] initWithUTF8String:artistChars];
PaintingInfo *info = [[P开发者_开发技巧aintingInfo alloc] initWithUniqueId:uniqueId artist:artist];
[returnArray addObject:info];
[uniqueId release];
[artist release];
}
sqlite3_finalize(statement);
}
sqlite3_close(database);
return returnArray;
}
So, what I'm thinking is that one way could be to use a loop inside before adding the result to the returnArray, where I check if it matches a previous result... It sounds fairly simply, but for some reason, I haven't gotten the loops I've tried to work (think I might have been working too long without sleep, so I'm starring blindly at my errors)... Then again, I'm fairly new to SQLite, so it might be a poor way of going about it...
Any suggestions?
Why not let the sql engine do the work? Do a select distinct
http://www.sqlite.org/lang_select.html
example:
SELECT DISTINCT artist FROM Painting
If for some reason you need to do it in code in the loop as your processing, you can look at NSSet which is a hash set. You would add each artist to the set as you process it and check if in the set before processing.
http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSSet_Class/Reference/Reference.html
For example, this:
NSArray *artists = [NSArray arrayWithObjects:@"bob", @"jane", @"jane", nil];
NSMutableSet *distinctArtists = [[NSMutableSet alloc] init];
NSMutableArray *list = [[NSMutableArray alloc] init];
for (NSString* artist in artists)
{
if (![distinctArtists containsObject:artist])
{
[distinctArtists addObject:artist];
[list addObject:artist];
}
}
// print
for (NSString *artist in list)
{
NSLog(@"artist: %@", artist);
}
outputs:
2011-10-06 22:51:16.457 Craplet[1982:707] artist: bob
2011-10-06 22:51:16.459 Craplet[1982:707] artist: jane
SELECT * FROM Painting GROUP BY Artist had the same effect
精彩评论