A Core Data Primer

Everyone’s first encounter with Core Data would be through books and the occasional glance at the documentation. No one tells you what are the base tips in bullet points that you need to know. Having worked on Core Data for the past 9 months, I thought it’ll be a service to the community to at least commit something to Google’s memory.

  • Everything except NSManagedObjectContext is thread safe.
  • Create NSManagedObjectContext in new threads prior to using them. Pass them the NSPersistentStoreCoordinator of any NSManagedObjects across threads is fine.
  • NSManagedObjectID is your friend. Always use it if you are doing threading.
  • NSManagedObjectID is sometimes temporary. Use obtainPermanentObjectIDs to ensure that they are permanent.
  • Getting a permanent ID might cost disk access so use wisely.
  • Process cross context saving on the thread that the NSManagedObjectContext was created.
  • Instrument’s time profiler is your friend to find where Core Data calls are taking a long time.
  • Additionally, you can also get SQL statements that are generated as debug messages in console by turning on a flag.
  • Use as little relationships as possible when fetching objects. Easier to fetch criteria based on the actual operating object and have the fetch also fetch all relationships.
  • Sometimes it is easier to spin off a thread to fetch results and process them before calling the completion block with results.
  • Have a manager to handle all Core Data fetching of objects instead of being smart and trying to have individual managed object subclasses handle everything.
  • NSFetchedResultsController is sometimes a bitch when sending notifications of changed content. Don’t use UITableView’s reloadSectionsWithAnimation and its siblings when crashy happens.
  • Don’t look into [NSManagedObjectContext registeredObjects] to get objects back. They might already have been deleted but still cached. Stupid stupid me.
  • Always test Core Data performance on device.
  • Always do fetches on entities that you are filtering criteria for then use inverse relationships that are prefetched to get the data you really want (Basically think topsy turvy; less database joins the better because this is an object graph).
Event-ed NSURLRequest

Have been very much inspired by the work on nodejs. For those of you who don’t know, nodejs is a basically a system to do Evented I/O using Google’s V8 Javascript engine.

One such application of nodejs is the development of servers both HTTP or socket based that doesn’t require the spinning up of threads to handle connections and/or network events. Callbacks are assigned to events and when those events happen, the callbacks are ran. No threads, easy peasey, low overheads, etc.

Currently there are 2 ways to do NSURLRequests. You can either wrap it around a thread and execute the operation synchronously or implement its delegate methods and have it run within the runloop.

JOURLRequest is an encapsulation of the NSURLRequest and its delegate methods to provide for a way to easily implement run loop based event-ed NSURLRequests.

Read More

Universal Framework

Universal Framework Project Setup

I’ve always loved backend code to be as cross platform as possible. Writing everything based upon Foundation and CoreFoundation only is one of the ways to do that and I’ve always strived to adhere to that principle as much as possible.

While that is cool, the problem begins when you actually want a universal library to work on both OS X and iOS. There is no such thing as Xcode clearly separates both. Understandably, this is seems to be an engineering and architecture decision. Still it would be cool to have a library that you can drop in either your OS X or iOS project.

There is largely 2 schools of thought.

  1. Create your own .framework directory structure
  2. lipo your own static library

There is inherently more flexibility with option 1, but the complexity of building such a framework is huge. Additionally it doesn’t allow you package everything in an Xcode project that can act as a dependency in your other projects.

Using lipo presents its own problems too as a Fat binary must contain code for unique architecture. In short, you cannot have a fat binary with code for the iPhone Simulator and OS X as both contain the same architecture.

After much experimenting I’ve figured out my own solution for this which I feel gives a much better workflow. The genius of the solution is that independently the project will build and create fat binaries for both iPhone Device + iPhone Simulator as well as iPhone Device + OS X.

Additionally, it can be added to existing projects as a dependency and build the appropriate static library which you can then use to automatically link to your project.

One thing to note though with this approach is that if you have the usage of Categories in your code, you will have to add to the Other Link Flags configuration of the Xcode build settings the “-ObjC” flag. Related Technical Q&A here.

Currently two of my projects use such a method of sharing code.

***Update: If you are using the dependency way of getting things done, just link to the “Device” build target. Every time you want to switch the build target you are working on, just do a Clean all. Xcode will build the architecture of either the simulator or the device depending on selection.

On to the steps.

Read More

… one down.

A year back, I attended my first WWDC. It was a fantastic experience and upon coming back, I set to create an iPhone app as a precursor to starting development on the Mac.

Now the inspiration simply came from splitting the bill with friends when we went out to eat. I set to create a replica of an actual check and gave an iPhone user the power to accurately get the amount payable per person based upon the numerous taxes and weird charges that local eateries have.

It was an exciting time, I came up with concept art, I coded, I designed. Then reality set in and school consumed me. I had interesting ideas about the input methods and various other functionalities.

I never really did get to it ever again despite getting numerous prompts from friends to continue. I knew it had potential.

So when I was working on Traversity, I told myself it’ll be the next project once its done. Next because at that time and now, I know more than I used to, having pushed out a Mac app as well.

Then I found out about BistroMath.

The feeling was bittersweet. It was exactly the same idea, with a better UI. It was however something I am confident of coming up with if I had more time. I bought the app and spent some time playing around with it and was absolutely blown away by the whole thing.

It is simple, elegant and gets straight to the point. It was the whole thing I was writing about functional design. I loved the category selection. I loved the way you select and add other people to split the check with. It was genius. The intuitiveness of the whole process should not be underestimated as well. It is a fantastic product.

I’m happy that they didn’t butcher the idea. And sad that it wasn’t me that saw to its completion. So I’m dropping Go Dutch. Not really a point in duplicating features when they have such a sweet implementation.

I emailed the guys who worked on it with congratulations as well as a note to say that I’ve had something similar brewing in the works too. Daniel was nice enough to reply and I really hope to meet up with them come WWDC10.

Congrulations BlackPixel for shipping BistroMath. It rocks as much as I envisioned mine. :)

One up…

So yesterday Apple finally approved Traversity after 2 weeks in the App Review process. My education with regards to developing and deploying an app on the iPhone platform is more or less done. Save for bugfixes and feature improvements, Traversity should be on hold until I get the next app out.

Still, important lessons were learnt and it was a worthy project as a first foray into the whole thing. Go Dutch was not such a good platform, but I’ll save that for later.

So what did I learn?

  • MVC works. Bringing the model portion of the project into a stable state proved invaluable in speeding up development time with regards to the Views and the Controllers. There wasn’t much context switching with a rock solid model. It became just an exercise in getting the model API right and having the views and controllers happy together. 1 week of intensive model development = 2 weeks of pain free UI work. Traversity took 3 weeks to complete.
  • UI design should be functional. And 2 simple reasons at that. Familiarity and performance. If you really need functionality that does not exist in the system, try to logically extend existing controls. Make sure it makes intuitive sense and follows the HIG.
  • It helps if you can find a good designer when it comes to icons. UI helps too.
  • It is a bitch working alone. Between writing code, and designing the app, you still have to work on the publicity, the support options, the website, etc.
  • Version Control is your friend.
  • Its actually really fun!
  • Waiting for app review totally sucks. The rush to complete everything is just suddenly replaced by restlessness while you wait.
  • #ifdef means to remove the #define if you want to disable a feature.
  • Erica Sadun’s APIKit roughly catches stuff. Better if you just do otool and nm against known private APIs.
  • Its easy to talk about what you want to do, but eventually the best measure of everything is whether it is shipping. Prototypes are useless apart from saying that an idea exists.
  • A good release workflow helps speeds things up.
  • Strike a good balance between best practices and hackery to get things shipping.
  • Go back and do better by the hacks once you ship.

It was a fun experience nonetheless and I will be applying what I have learnt into the next app that I’m planning.

Xcode, there’s this thing about you.

There’s this curious thing about working on Xcode.

I’ve never seen myself, upon finishing a project, go immediately back to the IDE and start on a new one. Has never happened to me back in my Windows days with Visual Studio 5.0, 6.0, .Net and what not. Has never happened to me with NetBeans and whatever other incarnation of a Java IDE for school.

Maybe its just being a fan boy, but seriously, an IDE? Comparing Xcode to something that is more featured and complex like Visual Studio, you get a feel that Xcode is not truly in the the same game.

Hell, for newbies going to Xcode for the first time, its the most unintuitive POS ever. And yet, it still is a joy to work on once you get the hang of it.

I sometimes think, Objective-C has a part to play. But I can’t be sure.

Functional Design

Too often we get too caught up with features and frameworks available to us that we go overboard with using everything. There are many developers that overuse custom user interface elements, and others that misuse system user interface elements.

When I was developing Traversity, I was looking around to see how best to make the App look good. Of all the Apps on my iPhone, one that stood out the most was Tweetie. It was simple, thoughtful and very Apple-esque. That was where it hit me that the thoughtful or lack of usage of custom elements provides an infinitely better experience. That is unless you are Bjango or Tapbots.

Instead of throwing all your custom elements onto your app to showcase your design prowess, consider that perhaps user experience is more important than just plain aesthetic appeal. A picture is still a picture unless it does something after all.

Apart form following Apple’s guidelines, there are some additional things that should matter when thinking about design for iPhone applications.

  • Progressive Disclosure
    If there is not data to be displayed, removed the section completely from the tableview.
  • Custom, but not so custom
    Add features, not graphics to UI elements provided. Users expect familiar controls, but also will be delighted to know if they also provide additional solid functionality. Cue Facebook’s usage of a UIButton in the Nav bar to bring you back to the home view.
  • Performance
    No one wants a slow performing application. 
  • Flow
    At the end, it is also largely about information architecture. How and where you display/gather information and how they are related to each other. This provides context and easy understanding for the various functions of your App.

You don’t have to be an design god to make applications that work fantastically. Even little tweaks can help immensely.