Embedding long SQL queries in Objective-C source code

Thought I’d share a tip with you guys how to embed long queries in Objective-C source code. I think I found a pretty neat solution involving a couple of preprocessor macros and abusing the way string constants are concatenated:

#define QUERY_DO(query) static NSString *query = @""
#define QUERY_END @"";

That makes it possible to write code like this:

NSMutableArray *params = [NSMutableArray arrayWithCapacity: 7];
[params addObject: settings.username];
[params addObject: settings.password];
[params addObject: [NSNumber numberWithInteger: settings.lastSync]];
[params addObject: settings.selectedFeed];
[params addObject: settings.selectedFeedType];
[params addObject: settings.selectedEntry];
[params addObject: settings.selectedView];
"UPDATE settings SET "
" username = ?,"
" password = ?,"
" last_sync = ?,"
" selected_feed = ?,"
" selected_feed_type = ?,"
" selected_entry = ?,"
" selected_view = ? "
[DB execute: query with: params];

Not as awesome as in some more dynamic languages, but still more readable than having it on one line and without the overhead of loading from some external source (like XML) – every bit of performance on devices like the iPhone or iPad matters.

Hope this is useful to someone ;)

Tarmo Lehtpuu
Tarmo is the swiss army knife Software Engineer. His deep knowledge on wide range of technologies makes him an efficient problem solver. In addition to Ruby on Rails, he enjoys developing iOS Apps.

1 Comment

  • xhan

    hey, I am really impressed by your `code highlight style`, can you share us the theme and the plugin that you used in this blog?

Liked this post?

There’s more where that came from. Follow us on Facebook, Twitter or subscribe to our RSS feed to get all the latest posts immediately.