Cocoa

 
17
Feb
2012
 

Extending NSData and (not) Overriding dealloc

by Tom Harrington

A couple of weeks ago Matt Long was having a problem with an app running out of memory. He had a ginormous data file he needed to load up and process, and that memory hit was more than the app could bear. It would load just fine, into an NSData, but before he could finish with it the app would run short of memory and die.

Until recently the obvious thing would have been to tell NSData to create a memory-mapped instance. Given NSString *path pointing to a file, you could create an NSData with almost no memory hit regardless of file size by creating it as:

NSData *data = [NSData dataWithContentsOfMappedFile:path];

Starting with iOS 5 though, this method has been deprecated. Instead, what you’re supposed to do is:

NSError *error = nil;
NSData *data = [NSData dataWithContentsOfFile:path options:NSDataReadingMappedAlways error:&error];

So, fine, whatever, it’s a different call, so what? Well, it wasn’t working. Instruments was showing that the app was taking the full memory hit when the NSData was created. Mapping wasn’t working despite using NSDataReadingMappedAlways. So what could he do? The wheels of my mind started turning.

(more…)

 
11
Jan
2012
 

Handling incoming JSON redux

by Tom Harrington

A few months ago I wrote here about a generic approach to safely take incoming JSON and save values to Core Data object. The goals of that code were twofold:

  1. Provide a safe, generic alternative to Cocoa’s -setValuesForKeysWithDictionary: for use with NSManagedObject and its subclasses
  2. Handle cases where JSON data didn’t match up with what the managed objects expected. Getting a string where you expect a numeric value, or vice versa, for example, or getting a string representation of a date when you want a real NSDate object.

The first item was the most important. It’s tempting to use -setValuesForKeysWithDictionary: to transfer JSON to a model object in one step. The method runs through the dictionary and calls -setValue:forKey: on the target object for every entry. It has a fatal flaw though, in that it doesn’t check to see if the target object actually has a key before trying to set it. Using this method when you don’t have absolute control over the dictionary contents is an invitation to unknown key exceptions and nasty app crashes.

Fixing this for managed objects was relatively easy because Core Data provides convenient Objective-C introspection methods. The general approach was:

  • Get a list of the target object’s attributes
  • For each attribute, see if the incoming dictionary has an entry. If so,
  • Compare the incoming type to the expected type, and convert if necessary.
  • Call -setValue:forKey: with that key and its value.

And then just last week I had the thought, wouldn’t it be nice if this worked for any object, not just for managed objects?

(more…)

 
2
Jun
2011
 

Saving JSON to Core Data

by Tom Harrington

Hi, I’m new here. You may know me as @atomicbird on Twitter. Just a few days ago my book Core Data for iOS: Developing Data-Driven Applications for the iPad, iPhone, and iPod touch (co-written with the excellent Tim Isted) was published, and Matt invited me to contribute some Core Data tips to CIMGF. I’m going to start off discussing taking JSON data from a web service and converting it to Core Data storage. Along the way I’ll cover how to inspect managed objects to find out what attributes they have and what the attribute types are.

Publishing lead times being what they are, this post covers information not included in the book.
(more…)

 
13
Mar
2011
 

Super Happy Easy Fetching in Core Data

by Saul Mora

First up, I want to thank Matt Long and Marcus Zarra for allowing me to guest post on CIMGF. This post is the first in a short series of topics describing how to I’ve made using Core Data a little simpler without giving up the power features you still need. The full project from which this series is derived is available on github.

Core Data, for both iPhone and Mac, is a very powerful framework for persisting your objects out of memory, and into a more permanent storage medium. With the enormous power of Core Data, it can be easy to slip into the trap of thinking that Core Data is very complex.

(more…)

 
1
Mar
2011
 

Subduing CATiledLayer

by Matt Long

Many technologies we use as Cocoa/Cocoa Touch developers stand untouched by the faint of heart because often we simply don’t understand them and employing them can seem a daunting task. One of those technologies is found in Core Animation and is referred to as the CATiledLayer. It seems like a magical sort of technology because so much of its implementation is a bit of a black box and this fact contributes to it being misunderstood. CATiledLayer simply provides a way to draw very large images without incurring a severe memory hit. This is important no matter where you’re deploying, but it especially matters on iOS devices as memory is precious and when the OS tells you to free up memory, you better be able to do so or your app will be brought down. This blog post is intended to demonstrate that CATiledLayer works as advertised and implementing it is not as hard as it may have once seemed.
(more…)

 
5
Jun
2010
 

Re-Ordering NSFetchedResultsController

by Matt Long

So Marcus is the Core Data guy, but I’ve been working with it a good bit myself lately and was recently faced with having to add re-ordering for a list of entities in a UITableView. The methods I found online for accomplishing this all suggested using an NSMutableArray as the data source for the table view. That will work, but I came up with another method, though similar, that achieved what I need without having to switch from using my NSFetchedResultsController as the data source behind the UITableView. In the end, I did use an NSMutableArray, however, I end up using it just to take advantage of its indexing. Read on to see what I mean.
(more…)

 
2
May
2010
 

My current Prefix.pch file

by Marcus Zarra

I have posted and discussed this file a few times but as with all things it has been touched, tweaked, and generally improved upon.

In this article we will discuss the latest iteration of my `Prefix.pch` file. As with anything I post, it is available for you to use as you see fit.

## The File

For those who don’t want to read the entire post, here is the file:

#ifdef DEBUG
  #define DLog(...) NSLog(@"%s %@", __PRETTY_FUNCTION__, [NSString stringWithFormat:__VA_ARGS__])
  #define ALog(...) [[NSAssertionHandler currentHandler] handleFailureInFunction:[NSString stringWithCString:__PRETTY_FUNCTION__ encoding:NSUTF8StringEncoding] file:[NSString stringWithCString:__FILE__ encoding:NSUTF8StringEncoding] lineNumber:__LINE__ description:__VA_ARGS__]
#else
  #define DLog(...) do { } while (0)
  #ifndef NS_BLOCK_ASSERTIONS
    #define NS_BLOCK_ASSERTIONS
  #endif
  #define ALog(...) NSLog(@"%s %@", __PRETTY_FUNCTION__, [NSString stringWithFormat:__VA_ARGS__])
#endif

#define ZAssert(condition, ...) do { if (!(condition)) { ALog(__VA_ARGS__); }} while(0)

This does not *replace* the Prefix.pch that comes with your project but it does go at the top of every project that I work on. The rest of this post we will review what this does.
(more…)

 
18
Feb
2010
 

Creating a NSManagedObject that is Cross Platform

by Marcus Zarra

An interesting question came up on Stackoverflow today so I decided to expound upon it in a short blog post.

A situation that I believe we are going to be seeing more and more often is one where application developers are writing multiple “versions” of their applications to be used on the desktop, their iPhone and now the iPad.

Because of that situation, it is becoming even more important that we write as much portable code as possible. Fortunately, our model can be completely portable between the two platforms.

(more…)

 
9
Jan
2010
 

The PragPub Magazine

by Marcus Zarra

Last month I was given the opportunity to write an article for The Pragmatic Programmers great magazine called “PragPub”. I am happy to say that the article I wrote for them was published in this month’s edition. The article, titled “Touching the Core”, is a walk through Apple’s great addition to the Core Data API for the iPhone.

Specifically this article walks through using the NSFetchedResultsController and some best practices in its use. The magazine is available for free on their website, [The Pragmatic Bookshelf](http://pragprog.com/magazines).

 
23
Dec
2009
 

Automatically save the dSYM files.

by Marcus Zarra

For those not aware, when you compile an Objective-C application, whether it be for the desktop or for Cocoa Touch devices, the debugging symbols are stripped out of the binaries. Therefore, unlike other languages such as Java, when a crash occurs, there is virtually no way to determine where the crash occurred. However, when the applications are compiled, a dSYM bundle is generated. This bundle allows us to match up the debugging symbols with the application’s crash log to help determine the cause of the crash.

(more…)

 
31
Oct
2009
 

Limiting 64-bit to 10.6

by Fraser Hess

Now that we’re all using XCode 3.2 on Snow Leopard (you are, right?) and building 64-bit apps you may find that not everything 64-bit works when your app is run on Leopard.
(more…)

 
20
Oct
2009
 

Marching Ants With Core Animation

by Matt Long

Marching AntsOur Core Animation book should be available by the end of the year. Go ahead and pre-order it now at Amazon if you would like ;-). When we started writing for Addison-Wesley back in September of 2008, I had no idea how long to expect it to take to finish a technical book as this was my first. One thing I discovered though, is that it is when you are about ready to go to production you start to realize all of the things that you probably should have added to the book, but didn’t think of in time. This blog post will cover one such item as a way to make up for not thinking of it in time. I may include this in a second edition if there is one, but consider this one a freebie. (more…)

 
24
Jan
2009
 

Dropping NSLog in release builds

by Fraser Hess

NSLog() is a great tool that helps debugging efforts. Unfortunately it is expensive, especially on the iPhone, and depending on how it’s used or what you’re logging, it could leak sensitive or proprietary information. If you look around the web, you’ll find a few different ways to drop NSLog in your release builds. Here is what I’ve put together based on those.
(more…)

 
25
Nov
2008
 

Adding iTunes-style search to your Core Data application

by Fraser Hess

iTunes has a very neat way of searching your library, where it takes each word in your search and tries to find that word in multiple fields. For example, you can search for “yesterday beatles” and it will match “yesterday” in the Name field and “beatles” in the Artist field. The basic predicate binding for NSSearchField provided by Interface Builder is not complex enough to archive this kind of search. I need to build the predicate dynamically since I can’t assume what field the user is trying to search and that each additional word should filter the list further – just like iTunes. Here is how to go about adding iTunes-style searching.
(more…)