7
Jan
2011
 

Passing around a NSManagedObjectContext on iOS

by Marcus Zarra

**This article is reprinted from the MDN**

The documentation on Core Data for the iPhone has lead to some confusion about how best to use Core Data on a Cocoa Touch device. One particular section seems to be the most confusing, specifically:

> A view controller typically shouldn’t retrieve the context from a global object such as the application delegate. This tends to make the application architecture rigid. Neither should a view controller typically create a context for its own use. This may mean that operations performed using the controller’s context aren’t registered with other contexts, so different view controllers will have different perspectives on the data.

> When you create a view controller, you pass it a context. You pass an existing context, or (in a situation where you want the new controller to manage a discrete set of edits) a new context that you create for it. It’s typically the responsibility of the application delegate to create a context to pass to the first view controller that’s displayed.

The idea behind this section is the issue of rigidity. Ideally, each view controller should be an island on its own. It should not rely on its parent, nor should it rely on the Application Delegate. Once a view controller is pushed onto the screen it should ideally be its own master.

## Why Rigidity is bad

It is fairly common when designing a Cocoa Touch application to “hard code” everything. Take the following navigation controller design:

![Navigation Controller Design](http://www.cimgf.com/wp-content/uploads/2011/01/Image1.png “Standard Navigation Controller Design”)

When this design, it is common to code each view controller and make it “aware” of its parent. In that design, it would be common to see view controller B call methods or call back (to its delegate) view controller A. While there is nothing technically wrong with this design, it is very rigid. It is nearly impossible to either move view controller B to another location in the stack or to reuse view controller B somewhere else. This is the trap that the documentation is trying to help new developers avoid.

## Solution One

Again using a standard/normal navigation controller design, it is expected that the detail flows from left to right. The left most (or root) view controller contains the most vague information and the right most (or deepest) view controller contains the greatest detail.

![UIFetchedResultsController](http://www.cimgf.com/wp-content/uploads/2011/01/Image2.png “UIFetchedResultsController”)

In this case then the best solution is to use a UIFetchedResultsController. This controller can be considered a thin layer between the view controllers and the Core Data bits. The advantage is that the UIFetchedResultsController is designed to work with tables. The other advantage is that your least detailed view (the root most likely) can listen as the delegate of the UIFetchedResultsController for changes and update itself.

In this design, however, instead of passing around a context, you would hand off just the entity that the child view controller needs to know about. The Core Data Recipes example provided by Apple illustrates this design quite well.

How does this break rigidity? Each view controller, from the root on down, only knows what is passed into it. The root gets the UIFetchedResultsController passed into it. The child views only get the items it cares about passed into it. None of them care what their parent view controller is. There is no call back to a parent.

## Solution two

What happens when we don’t have a typical navigation controller design? Perhaps a child view can pop up a modal view that displays different information. Perhaps a child view, for whatever reason needs to access information that cannot be directly passed into it every time.

In these cases there are a few different options.

### View already has a NSManagedObject

Following our example above, lets say that view controller C needs to create a new object. Perhaps it is a detail view of a recipe and the user wants to add a new recipe type (perhaps she is a vegan and just discovered there is no vegan type in the list). In this case we have passed in an entity (the recipe) but not a reference to the NSManagedObjectContext. Fortunately this solution is easy to fix. The NSManagedObject retains a reference to its NSManagedObjectContext internally and we can access it. Therefore we can easily retrieve the NSManagedObjectContext from the NSManagedObject and create the new Type entity and pass it to the modal child or whatever our design calls for.

This again avoids rigidity because the view controller that represents the entity does not need to call up to a parent object or the UIApplication delegate. It is self contained and only manages view controllers that are down stream from it.

### View does not have a NSManagedObject

In this situation things are *slightly* more complicated. In this case we want to create a @property for the NSManagedObjectContext and require that our creator set the property.

@interface MyViewController : ViewController
{
NSManagedObjectContext *moc;
}

@property (nonatomic, retain) NSManagedObjectContext *moc;

@end

Again, the view controller is an island of its own because it does not care where that NSManagedObjectContext came from. All it knows is that it is required for the view to function. It does not care of it is a new NSManagedObjectContext specifically created for its use (perhaps for a cancelable edit tree) or if it is the same NSManagedObjectContext that has been passed around since the launch of the application. All it knows is that it has the elements it needs to perform its function.

By making the NSManagedObjectContext a settable property we can also transplant the view easily. If, at some point in the project lifecycle, we decide that it makes more sense to have the following design:

![Modal View Controller](http://www.cimgf.com/wp-content/uploads/2011/01/Image3.png “Modal View Controller”)

Taking from Apple’s Recipes Application, perhaps we decide that moving from the table view directly to the image of the recipe is more pleasing to the users and that when they want to see how to make it they can “flip” the image over and see the detail.

Making this change with each view controller being an island is quite simple. We just rearrange the views without having to worry too much about breaking the application.

## Solution three

Up until now we have been looking at just a navigation controller design. But what about tab bars? In the situation of a tab bar we again want to avoid rigidity because it is even more common that tabs will get moved around.

The solution to this is to again use a @property for the NSManagedObjectContext and require that the creator set this property before the view is displayed on screen. If you are creating the tabs in code this is trivial because you are already calling init on the view controller and you can add one more line of code after the init to set the property.

If the user interface is being developed mostly in Interface Builder it is slightly more tricky. Personally I am not a fan of creating navigation controllers or tab bar controllers in Interface Builder. However if that is the design then I would recommend referencing the view controllers as properties and passing along the context upon initialization of the application. It may be possible to do this entirely in Interface Builder but I am not comfortable enough to recommend that as a solution.

## Conclusion

The overall idea behind this article is to keep each view controller separate from anything up stream or in a different silo. This will make the design far more flexible in the long run. Any time that you feel the “need” to pass in a parent view controller to a child view controller, reconsider the design. Consider using a @protocol delegate design or NSNotification calls instead. Keep each view controller as its own private island.

 
29
Sep
2010
 

iPhone DevCon 2010

by Marcus Zarra

Just finished with the iPhone Dev Con 2010 in San Diego and it was a very pleasant conference to go to. The organizers definitely have a nice balance and treated the speakers well. I enjoyed the trip and I hope that everyone who attended my sessions got something out of them.

As I promised in the sessions, here are the slides and sample code.

* [NSFetchedResultsController](http://cimgf.s3.amazonaws.com/NSFRC_iPhoneDevCon10.pdf)
* [Importing and Exporting Efficiently](http://cimgf.s3.amazonaws.com/Import_Export_iPhoneDevCon10.pdf)
* [Importing Example Code](http://cimgf.s3.amazonaws.com/Import_Example.zip)

And the ZSContextWatcher is located in our [open source git hub project](git://github.com/ZarraStudios/ZDS_Shared.git).

Thank you to all of the attendees for having me and I look forward to seeing everyone at the next conference.

 
20
Sep
2010
 

Call for Papers

by Marcus Zarra

I remember when C4 started, the first year was a huge amount of excitement. There were going to be people at that conference, speaking at that conference, that were legends in the Mac community. The idea of being able to hear them share the secrets to their success was simply invaluable.

I regret missing that first C4 conference.

In December of this year is another opportunity for that first. The guys who put together the 360 iPhone conferences are taking the plunge and putting together a Mac conference this December. Who is going to be there?

**That is the really cool part!**

They are doing a [call for papers *right now*](http://www.360macdev.com/call-for-papers/). You can be a part of the first experience of this brand new conference. You can help make it great and make it a must attend conference.

I have submitted my paper to speak and I know I will be attending even if I do not speak.

Will I see you there? I hope that I do.

 
15
Jul
2010
 

Core Data and Encryption

by Marcus Zarra

Just a quick post to point out a great article written by Nick Harris of NewsGator fame. He has looked into the issues with Core Data and encryption.

Core Data and Enterprise iPhone Applications – Protecting Your Data

It has always been a difficult question and fortunately Apple has addressed it for us. Even better, Nick has shared the code so we don’t even need to try and discover the solution ourselves.

Thanks Nick!

 
12
May
2010
 

WWDC 2010 T-Shirts

by Marcus Zarra

In celebration of the late notice of WWDC this year; CIMGF is offering late notice on our T-shirts!

In previous years I took orders and then delivered them to you at WWDC. I discovered something from that it. It was a huge pita for everyone involved. Therefore, this year I am going to do it differently.

I have created a storefront on SpreadShirt where you can order one of several different T-shirts (and a jacket) for this year’s WWDC. The new shirts include the new CIMGF logo which will soon adorn this beloved site.

I hope to see many of you wearing the T-Shirts this year in San Francisco!
WWDC 2010 T-Shirt

 
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:

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…)

 
24
Jul
2009
 

Voices That Matter Conference

by Marcus Zarra

October 17th and October 18th of this year, the Voices That Matter conference will be occurring in Boston. I will be speaking at this conference on the subject of Core Animation. In addition to myself, there is a very nice list of speakers at this conference including Aaron Hillegass, Daniel Jalkut, Fraser Speirs and many others.

Voices That Matter

Early Signup

Currently, you can get $200.00 off the the price of the conference if you sign up before the 12th of September.

In addition, if you use the speaker code ‘PHASPKR’, you can receive an additional $150.00 off the price. That is a combined discount of $350.00 if you sign up before September 12th.

http://www.voicesthatmatter.com/iphone2009/

 
8
May
2009
 

MacBook Pro looking for a good home

by Marcus Zarra

Having finally decided that I prefer the 1920×1200 display of the 17″ Macbook Pros I am finally committing to one size of laptop. To help force myself into that commitment I am going to be selling my gently used late 2008 15″ Macbook Pro.

The specs are:

* 2.53 Ghz Intel Core Duo
* 4GB RAM
* 320 GB Harddrive
* 512 Nvidia Video cards (9400 and 9600)
* 2 USB
* 1 FW/800

All of the original hardware and equipment are included.

The asking price is $1,800.00 plus shipping.

The machine is in perfect condition as shown in these photos on flickr (http://tr.im/kQ11).

If you are interested in this machine please contact me at marcus at cimgf dot com.

 
3
May
2009
 

Core Data and Plug-ins

by Marcus Zarra

Thanks to the ability to have configurations in a Core Data Managed Object Model and being able to save data to multiple Persistent Stores, it is possible to have a Core Data Model that is constructed from not only an internal model, but from the models of all the plug-ins that are loaded into the application.

In this example we are going to build a basic application with the following requirements:

  • A plug-in framework
  • Plug-ins can extend the managed object model of the application
  • Removal of a plug-in should not corrupt the persistent store.

(more…)

 
3
Apr
2009
 

WWDC 2009

by Marcus Zarra

I am happy to confirm that I will be at WWDC this year in San Francisco. I am making this trip a little tighter, time-wise than I have in the past so I will be arriving on Sunday, June 7th and leaving on June 13th.

I normally post my nighttime plans on twitter (@mzarra) so if you are interested in having a chat then that is the best way to track me down. I will also be tweeting which sessions I am going to throughout the day.

I look forward to seeing everyone there, it should be very interesting as always.

 
26
Mar
2009
 

Don’t Blindly Trust D.E.B.B.

by Marcus Zarra

In some recent discussions I have been shocked to realize that many developers treat DEBB as gospel. This is a terrible idea. DEBB is written by people like me and I am a moron.

(more…)

 
26
Feb
2009
 

Don’t Screw Your Customers Over

by Marcus Zarra

As part of working with the print world I occasionally have to actually print something out. Publishers like to have paper copies of contracts, tax documents, etc. Its a pain in the rear and outdated but a necessary evil at this point.

One such occasion happened today and I needed to mail out a new signed contract to THe Pragmatic Programmers. As luck would have it, I lost my aging copy of Mail Factory, an app that prints nice mailing labels, since the last time I needed to print a label. No big deal, I went to their website and tried to download a new copy. Since the last time I used it, about a year ago, they have cancelled that product and rebranded it Labels & Addresses. Still no big deal, I downloaded the new application and recreated my label.

When I went to print the label I saw in the preview window that they printed “trial version” on the label. Ok, now this is starting to get annoying. If you are going to let me demo the software, let me demo it! Don’t put trial version on the very first label I try to print!

I took a deep breath, remembered that I have been using their software for many years now and decided to just buy a license. They even took my old license in and gave me a discount. Blood pressure dropped, things were fine. Then I ran into their payment processor — Digital River.

I am stunned, stunned, that anyone is still using these thieves! Immediately they try to charge me a “license backup” fee which is an Opt-Out. Annoyed, I opt out of that. On the payment page I have a choice for PayPal. Surprise, there is a $3.50 “manual processing fee” for PayPal. This is NOT 1998! Still, I wanted to print a pretty label so I back out, add a credit card and hit process. I am then presented with this:

SWREG - Error
Uploaded with plasq‘s Skitch!

Did my order go through or not? Who knows? I check my credit card provider, no charge. But are they slow or did it fail?

I contact the software vendor but they are only open until noon EST. Guess I will find out tomorrow or the next day since their site claims they strive to respond within 1-2 days. A happy customer this does not make.

Advice

Do not do this to your customers. Stop using these payment processing services that charge you insane amounts of money and screw your customers over. Spend a day (yes it only takes ONE day) and write your own that links to Google or PayPal. Or just use E-Junkie like I do. This is a customer facing system. When you bend your customers over with additional fees, cryptic error messages and other junk, they are not going to come back to you and say “please sir I would like some more”.

Also, respond to customer email within 24 hours. Don’t let it sit. Don’t give your customers a 7 hour window per day that you handle email. This is just bad.

My Solution

I deleted their software, will be asking for a refund (IF they ever charge me) and I wrote the label by hand. I will not be going back to them any time in the future for any of their software unless they stop using Digital River.