Search Results for: core data

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

 
14
Oct
2011
 

Parent Watching Its Child

by Marcus Zarra

Recently on [StackOverflow](http://stackoverflow.com) I have seen several questions regarding the desire for a parent Entity to be updated whenever an attribute within the child has changed.

There are several different ways to solve this problem. The easiest is to have the child ping the parent whenever it changes and then the parent can update any values it needs to as a result of that ping.
(more…)

 
28
Jul
2011
 

Conference: Update 2011 (Brighton, UK)

by Marcus Zarra

When: September 5-7, 2011
Where: Brighton, UK

[Schedule and Additional Information](http://updateconf.com/)

I am very pleased to announce that I will be speaking in Brighton at the Update conference starting on September 5, 2011. The Update conference is a bit different than the normal “developer” conference that I attend and speak at. Instead of just or primarily focusing on the developer; a great deal of focus is put upon the user and the user experience. If you have been in attendance for any of Aral Balkan’s talks then you know very well what his focus is.

In addition to speaking at the conference I will be giving **two** one day workshops on Core Data. The first workshop will be an introduction to Core Data. I hesitate to call this a beginner workshop because *you*, the attendees, will be directing the workshop. If everyone wants to start at step one then we will. However throughout the day you will be setting the pace of what we learn and discuss. This format has worked very well in the past and the last time we did a workshop like this the day ended with some pretty advanced discussions.

The second session is labelled advanced and will be starting off with the assuming that we all know and understand the principals behind Core Data. In this session we will deep dive into some of the more complex areas of Core Data. Again, I have a list of topics but you, the attendees, drive the session. Therefore it is intentionally open ended so that you can come with your questions and problems and we can discuss them together. I plan on wrapping up the second workshop with some real world examples of edge cases and situations I have run into and how they were solved.

I invite you to join me in Brighton this September to attend Update 2011. I expect it to be a great time.

 
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](https://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](https://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](https://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.

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

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

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

 
23
Apr
2008
 

Cocoa Tutorial: Don’t Be Lazy With NSDecimalNumber (Like Me)

by Marcus Zarra

NSDecimalNumber is Objective-C’s solution to numbers that need to be very precise. The documentation defines it as:

NSDecimalNumber, an immutable subclass of NSNumber, provides an object-oriented wrapper for doing base-10 arithmetic. An instance can represent any number that can be expressed as mantissa x 10^exponent where mantissa is a decimal integer up to 38 digits long, and exponent is an integer from –128 through 127.

NSDecimalNumber

If you are dealing with currency at all, then you should be using NSDecimalNumber. However, since it is immutable and definitely not a primitive then it is difficult to use right? Well — yes — a bit. But if you do not want to see your $9.50 item displayed as $9.49999994 or something then you are better off using NSDecimalNumber right from the beginning. Otherwise you are going to be converting to it later and that is a LOT more painful.

(more…)

 
15
Apr
2008
 

Cocoa Tutorial: Get The Most Out of Key Value Coding and Observing

by Marcus Zarra

Key Value Observing/Key Value Coding (KVO/KVC) is probably one of the most powerful and most under-utilized features of Objective-C. Here are a couple of examples of how to get the most out of it

When a call is made on an object through Key Value Coding such as [self valueForKey:@”someKey”], numerous attempts are made to resolve the call. First, the method someKey is looked for. If that is not found then the iVar someKey is looked for. If neither of those are found, then one last attempt is made before presenting an error. That last attempt is a call to the method -(id)valueForUndefinedKey:. If that method is not implemented then an NSUndefinedKeyException is raised.

valueForUndefinedKey: is designed so that when you request a value from an object using -(id)valueForKey: the object has a last chance to respond to that request before an error occurs. This has many benefits and I have included two examples of those benefits in this post–Core Data Parameters and Data Formatting.

(more…)

 

About

by Marcus Zarra

The site is called Cocoa Is My Girlfriend because it’s about programming and a passion for programming on iOS and OSX. Writing code is hard work but it’s fun. It’s science but it’s also art. It’s fun as well as infuriating. It’s often beautiful and sometimes ugly. It’s temperamental yet rewarding. Cocoa is My Girlfriend.

We got the original idea from a phrase in the song Apple used for their first iPod Touch commercial called ‘Music Is My Hot, Hot Sex’ by Brazilian group Cansei de Ser Sexy. The phrase that says ‘Music is my boyfriend’ and then ‘Music is my girlfriend’ is what caught our attention. It’s interesting way to say, we really like writing code using Cocoa.

About The Authors

Marcus S. Zarra is best known for his expertise with Core Data, persistence and networking. He has been developing Cocoa applications since 2004 and has been developing software for most of his life.There are very few developers who have worked in more environments, on more projects or with more teams than Marcus has. Marcus is currently available for short to medium term development contracts, code reviews and workshops. If your team is struggling with code structure, networking, or persistence please contact him. He would love to help your team produce the best application possible.

Marcus is the author of Core Data: Apple’s API for Persisting Data under Mac OS X and Co-Author of Core Animation: Simplified Animation Techniques for Mac and iPhone Development. You can find Marcus on Twitter at @mzarra or via email using marcus@cimgf.com.

Matt Long: Matt is a solid applications engineer who has used many different technologies throughout his career. He has developed everything from web applications, mobile applications, and embedded device interfaces to iOS applications for the iPhone and iPad. He brings many years of experience that he uses to help teach other developers how to transition from the world of other development platforms to iOS and Mac OS X with greater ease. Matt is also a Co-Author of Core Animation: Simplified Animation Techniques for Mac and iPhone Development. You can find Matt on Twitter at @perlmunger or via email using matt at cimgf dot com.

Fraser Hess: Fraser Hess is the owner of Sweeter Rhythm LLC in Centennial, CO. He learned to programme on a Sinclair ZX Spectrum in his native Scotland, many moons ago. Prior to coming to Objective-C/Cocoa he learned BASIC, Pascal, PHP and even a little Ruby. Somehow he has a knack for fixing bugs in code he’s never seen, written in languages he’s never read. Fraser occasionally attempts to communicate with Americans through public speaking at events like RMOUG, C4[3] and 360MacDev. Fraser tweets in a thick brogue at @fraserhess and can be also be contacted at fraser at sweeterrhythm dot com.

Saul Mora: Saul Mora is the Founding Panda at Magical Panda Software. Saul is a relative newcomer to the Cocoa platform, having bought his first Mac when Apple first switched to Intel processors. However, Saul has a strong foundation in development fundamentals and has experienced a wide range of development platforms from Java, to C# and .net to Ruby on Rails. Saul contributes regularly to local iOS and Cocoaheads user groups and conferences sharing what he’s learned about iOS and Cocoa. Saul is the maintainer of the open source Core Data helper framework, MagicalRecord, described in a few posts here on cimgf.com. Saul is also the host of NSBrief, a podcast for Cocoa developers, talking about interesting developer-y topics. You can catch Saul on the internets at saul @ magicalpanda dot com or on twitter at @casademora.

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

 
12
Feb
2010
 

Accessing The Cloud From Cocoa Touch

by Matt Long

Everything is moving toward the cloud and unless you’re building calculators, unit converters, or miniature golf score keepers your iPhone app needs to know how to get data from it. In this blog post I intend to demonstrate how to set up a simple server application and how to retrieve data from it and post data to it using Cocoa Touch. I have chosen to use PHP on the server side because of it’s simplicity and ubiquity, and because I’ve know it, somewhat. You should, however, be able to implement something similar using your server side language of choice.

In many cases when you go to access remote data, you do so through a web service API. While services based on such technologies as SOAP or XML-RPC are standards that provide reasonable methods for retrieving and updating data, REST seems to be the methodology gaining the most ground lately. For our purpose in this post I won’t get into great detail of how to implement a REST base web service as, again, REST is not a specific implementation but rather a methodology. (Read up on it elsewhere if you don’t understand what this means). However, I will talk about it briefly so that you can get on the right path for doing your own REST implementation.
(more…)

 
8
Mar
2008
 

Cocoa Tutorial: How to Crash Cocoa

by Marcus Zarra

This article is designed to serve multiple purposes. First, it is to educate which I hope that it will. Secondly, it is a personal memory so that if (when!) I run into this issue again, I will be able to use Google to find this post and remember why I am an idiot and why the default settings for things are not always the best settings.MenuCrash.zip

First as always, here is the project that goes with this article.

If you run this application you will see that it does basically nothing. The interesting part of this app is how it crashes. To crash this application, perform the following steps:

  1. Open the application.
  2. Select the Application menu.
  3. Select the About window.
  4. Close the About window.
  5. Open the Application menu again.

(more…)

Copyright © 2024 Cocoa Is My Girlfriend