Cocoa Design Patterns

Erik M. Buck, Donald A. Yacktman

Mentioned 25

Provides information on Cocoa design patterns along with data models, AppKit views, bindings, and controllers.

More on

Mentioned in questions and answers.

I am a new iphone app developer.I want to know what is the difference between view and viewcontroller.

Are you familiar with the Model-View-Controller pattern? Before even starting iPhone development, you should be familiar with it. I recommend the book Cocoa Design Patterns. Trust me, it will help a lot in the long term.

So I'm new to iOS development and am doing all I can to learn the "best" way to do things. (Yes I know that's a relative term)

I'm coming from a world of C# and Java where we do things like injecting dependancies via an IOC container, use a repository pattern to abstract data access, use domain services and objects to encapsulate business data and behavior, etc. These are things I have yet to see in iOS development. (Maybe I'm looking in the wrong places)

I realize that Objective-C is a superset of C and a dynamic/loosely-typed language which will probably change the game quite a bit when it comes to good designs practices. Can anyone point me in the directions of some books/blogs/other that would help me make this mental leap from a strongly typed, managed environment to this new world while keeping my designs supple and abiding by the SOLID principles?

EDIT - I want to be clear here. I am not asking how to learn the Cocoa framework and the ins and outs of Objective-C as a language. I have found plenty of resources on that. I'm looking to take this to the next level, begin doing TDD and make sure the projects I'm building will be easy to extend and maintain.

There is a plenty of design patterns specific to the Objective-C and Cocoa development, you will find a very nice summary in this book. It covers language built-in patterns as well as some more complicated and high-level (architectural if you like) patterns.

In general, SOLID principles apply and are no less relevant in a dynamic language as they are in a strongly typed one. The other thing is that in Objective-C you have the option of using strong types in your design so pretty much all "classical" OOP patterns apply, although there may be some framework / language constructs more elegant and suitable for the job.

I have been developing web apps (primarily) using php and a bit of python, mysql, etc for many years now. I have a reasonably good grasp of objective-based development, and use objects as much as possible in my projects, although I certainly don't take full advantage of them. I am comfortable enough to be dangerous with C++,C, and have even touched a bit on ruby.

All that said, Objective C is giving me a very hard time. Not sure if it's the syntax, the file structure, etc, but i'm just not grasping how to properly put together the different components of an app, despite having gone through a few tutorials and explanations online. I have xcode, and have tried doing some basic stuff, but get lost quickly in real implementation.

My question: Can anyone recommend me a really solid book/books with some good examples that I can walk through to help me understand this language better? I am primarily interested in database interaction (or xml parsing) and audio streaming/delivery capabilities.

Any suggestions would be very much appreciated! Thanks!

The official documentation is great:

This is a great book. You need to understand Objective-C before you start jumping into creating apps (Cocoa Touch):

This is a great intermediate book:

This is a great forum to learn stuff, in addition, obviously, to here:

The Apple developer videos are also great, and you can download them with iTunes if you want, to have them on the go:

Also, check out the Stanford iPhone Programming Class videos on iTunes.


Here is the docs on Apple's XML class, NSXML:

And if you're going to be using databases, they'll probably be SQLite, and you'll definitely want to check out this wrapper for SQLite:

I found Aaron Hillegass' book really helpful in learning Objective-C

iPhone Programming Big Nerd Ranch Guide

There are a bunch of good chapters that walk you through creating your own apps you can deploy right to your iPhone/iPad or run in the simulator. He explains some of the heavier concepts i.e. Core Data really well.

Other than that the Apple Developer docs are a great and invaluable resource.

this would be my first question after signing up! Anyway heres my question, I did Java at university and I was always told I am a good programmer. However I never pursued it as a career - I went into support and management instead. Im pretty much bored with my job, I have therefore started to learn Objective C so that I can develop apps for the iphone. I am currently watching several different Videos / Books.

My problem is that when I go through the Apple documentation, although I understand most of it, sometimes I stumble. I believe that because you/we have the Apple documentation (i.e. Framework references) , everything should be clear, and therefore you should have no need to refer to a book or video (in order to learn how to use a particular class). But I alway do refer to a book and video and subsequently feel guilty as I believe the framework reference should be enough. (I therefore feel I am not up to being a programmer)

I also believe that you shouldn't need example code in order to learn how to use a particular class because Apple provides documentation for each class, but AGAIN I find my self googling example code and I find my answer like that - again I feel guilty for doing this.

Am I right in saying that Apple documentation is simply not clear? and that its ok to refer to a video/book or google? or forums for that matter?

I have proffesional programmers who tell me that I am worrying too much and that I should get on with it and use all the resources that I have. I just cant seem to get round this mental block that I have in my head.

When I start a programming project I am able to use the excellent search skills that I have to find the code I need, copy and paste it (yes I do understand it) BUT then I feel guilty telling myself that why didn't you think up the code yourself???? Therefore your not a real programmer, your just good at googling.

Currently I am going through 20+ books so that I can learn most of the frameworks, syntax etc to develop iphone apps. I believe if I do this, then when I think of a project I can make it quickly. Should I read a few books, like 2-3 and then just start a project /app , and if I get stuck just google it and get the code I need?

Can anybody please answer my questions?


Absolutely BRILLIANT answers and comments received from everyone. I am most grateful.

From now on I will use all the forums, books, documentation and example code I need without feeling guilty! As some people have said, Apple docs are not clear (and YES, I am very familiar with Objective C Syntax). I'll give you an example: In order to make the keyboard go away on the iphone, you have to use a method called resignfirstresponder. I learned how to use this method from a Video tutorial!

There is no way in hell that you can learn that from Apples docs, and sometimes not even from the best of books (the method is rather weird the way it works, the Apple docs are not clear).

Thats my gripe - Apple docs should be clear (at least with some example code). It seems people who are good programmers (but not good at googling) lose in this arena. And it seems not so good programmers can still get by - just by googling or watching a few videos (which a professional programmer does/cannot have access to for whatever reason). The whole affair seems rather unjust and imbalanced if you ask me.

Thanks for your replies people.

I think it would really benefit you to read Cocoa Design Patterns by Erik Buck. Once you start to see the patterns behind the frameworks, you start being able to anticipate how things will work through naming patterns and logic.

I am comming from an enterprise java development organization where we did development in nicely seperated re-usable layers. Persistency layers, Service layers, etc etc.

Now, I am looking for iPhone example apps or documentation on how to architecture complex iPhone projects. Most books & apple examples show you very limited code & architecture. They are not usable imo.

What I am also looking for is info on how to setup a continuous-integration build system which runs all my unit tests on code checkin & reports the unit test findings to a system where we can see the results. For our java projects, we use svn, mvn & sonar for this. What's apple's equivalent for this setup? Is it even possible?

So, to summarize my questions:
Q1: Are there any examples or books on complex iPhone project architecture?
Q2: How do we setup a continuous-integration build system?

How complex of an example would you like? This question links to a number of non-Apple open source iPhone applications, including my own. Some of the applications out there are relatively complex.

As far as design goes, I'd highly recommend the book Cocoa Design Patterns. While not strictly for the iPhone (given Cocoa's beginnings at NeXT and more recent presence on the Mac), the design patterns covered are core to the architecture of the Cocoa frameworks and Cocoa applications.

I'd also recommend paying for the WWDC 2009 videos and watching the sessions "iPhone User Interface Design", "Effective iPhone App Architecture", and "Prototyping iPhone User Interfaces". There are a lot of good suggestions for architecting iPhone applications in these sessions.

I've used unit tests with my applications, but I have not done any form of continuous-integration building. However, this question looks to have a lot of good information on doing continuous integration with Xcode.

Does anyone know of one? If it doesn't exist, anyone interested in collaborating to create it?

The delegate pattern is a design pattern that is pretty central to making the most of a number of UIKit classes. Apple's developer documentation pages (example) would be good web resources that collect information about related methods.

EDIT: Here's a page on Cocoa implementations of the observer pattern. Here's a book on Cocoa implementations of design patterns. With respect to iPhone development, KVO Cocoa bindings haven't yet been implemented.

I have created my first complex OS X application. While working on it, I've had some doubts about how I use the class that implements the NSApplicationDelegate protocol (the class Xcode creates by default for Cocoa applications, i.e. MyApplicationAppDelegate.m/h).

In many tutorials (and books), I see that people create an AppController class to manage main or generic application tasks. I prefer to add my generic tasks directly into MyApplicationAppDelegate and create specific controllers depending on the modules I need to manage.

For example, I add into MyApplicationAppDelegate every IBAction used to open other windows (i.e. opening a preference panel), every function that isn't strictly connected with a specific module/controller and IBOutlets for the main interface. In MyApplicationAppDelegate I also add every reference to controllers used in my application. That's essentially about it.

I'm really confused because I'm not sure whether or note this is good design. Has MyApplicationAppDelegate been designed for some other purpose?

I would like any suggestions and if possible any articles you might know of about design patterns for Cocoa.

Xcode used not to create an application delegate class in the Cocoa Application template by default.

I believe Apple only introduced the automatic creation of an <AppName>_AppDelegate class with their project template fairly recently, maybe in version 3.2 or so.

This is why many older books and tutorials have you create an AppController class, because the old project template did not create one for you.

You are free to use the <AppName>_AppDelegate as your main controller class, and the reason Apple adds it to their template is that so many developers use the NSApplicationDelegate object as their main application controller.

An excellent resource to learn more about design patterns in Cocoa is the book appropriately called Cocoa Design Patterns.

I'm not sure if I should create an abstract class and a series of descendants that inherit this abstract class, or define a protocol. What's the best practice in Cocoa?

Allow me to recommend a book called Cocoa Design Patterns it is a very nice book to look up how the Cocoa framework works and what paradigms are used.

Cocoa Design Patterns on Amazon

So I've run into this a few times, and am new to OOD so not sure if there is a good way to do this or not.

But basically, I have a MainViewController, and then I push a new DetailViewController. In my MainViewController, I have a Reset method that basically resets everything to their default values.

If I want to put the button to call Reset in the DetailViewController though, how do I call the method since it's in the MainViewController class?

What I've done before is have a reference to the ParentController (in this case, MainViewController), and then call it that way from the DetailViewController. I don't know if this is a good practice though and if there are better ways to do something like this.


You are following the "delegate pattern" and its one of the very good designs. I would recommend using the same approach. You can check out the book "Cocoa Design Patterns", it should provide you a good understanding of design patterns.

In your case, Create a delegate of type "id" in DetailsViewController, write properties for it and set it when you are pushing the DetailsViewController object from your main view. Then call the method using "ResondsToSelector" on that delegate. Let me know if you want a code snippet.

I am creating an application in which I have to pass data from 16 UITextFields, store them in an array in form of a class object and display all the objects from that array in other viewController.

How can you pass data from one viewController to the another?

Usually communication between unrelated view controllers is a symptom of ugly design. I'd avoid that.

A singleton object might be your best choice. Never ever use the application's delegate or NSUserDefaults to share data between objects. The same applies for saving data in a plist on disk and reload it from the other controller. That's just extremely bad design.

By the way: whatever is your skill level, get this book, Cocoa Design Patterns. It's not directly related to iPhone development, but it explains Cocoa's design and patterns in a clear way. Understanding it will help you a lot in designing your future applications.

I have a bunch of property data listed like this, but I am looking to write it much neater. What way would you recommend to write this neater? I have a lot more property data than these.

@property (strong,nonatomic) NSString *energyEnhancer;
@property (strong,nonatomic) NSString *energyEnhancer1;
@property (strong,nonatomic) NSString *energyEnhancer2;
@property (strong,nonatomic) NSString *energyEnhancer3;

I have to have property because I am passing data between view controllers.

The short answer:

The iOS Developer Collections Reference.

The Whole Story:

I think it would be a good idea to take a broader look at some of the Foundation classes that deal with collections, such as NSArray, NSSet, NSDictionary and if you're feeling particularly esoteric, CFBag.

Your question suggests that you could benefit from reading up on general Cocoa patterns. Indeed, you can pass just about anything from one object to another. An NSArray instance is certainly no different than several NSString instances.

For example, imagine we have an app called "PassingData" (GitHub link). I'm going to define a class which has our data, in this case, several "energyEnhancer" strings.

@interface PDDataSource : NSObject

@property (nonatomic, strong) NSString *engergyEnhancer;
@property (nonatomic, strong) NSString *engergyEnhancer2;
@property (nonatomic, strong) NSString *engergyEnhancer3;


Then in our view controller, we may try to access the energy enhancers, like so:

- (void)logDataSourceWithStrings {

    NSLog(@"Energy enhancer 1: %@", self.dataSource.energyEnhancer);
    NSLog(@"Energy enhancer 2: %@", self.dataSource.energyEnhancer2);
    NSLog(@"Energy enhancer 3: %@", self.dataSource.energyEnhancer3);

Another way to do this is like so:

- (void)logDataSourceWithArray {

    for(NSInteger i = 0; i < self.dataSource.enhancers.count; i++) {
        NSLog(@"Enhancer %i: %@", i, self.dataSource.enhancers[i]);

An added benefit to using an array is that you're no longer limited by the number of variables that you've declared at compile time. Your game or fitness app just got that much more robust.

This is only one way of accessing data that's in another object. Other strong contenders are delegate protocols, notifications, and callback blocks. Typically, if you're directly accessing data in another class, you're probably doing one of three things:

  1. Compositing: Creating a class that contains several objects that exist to help the parent class.
  2. Accessing a singleton. Singleton classes are universally accessible classes that can only be instantiated once. They're controversial, but there are appropriate use cases.
  3. Storing temporary state in an object.

If you want to model more than one kind of data, consider nesting your values (be it arrays, strings, numbers, or whatever) in a dictionary. This isn't always the case, though. I wouldn't want all of my classes to have a single NSDictionary property. Use your best judgement.

Another good strategy when modeling is to use the plist editor in Xcode to mock an object. Then you can make a class (or classes) that match the plist, in code.

It's really worth your time to familiarize yourself with the conventions and Cocoa Design Patterns. Lotsa luck!

I'm going through a refactoring and reorganization of my application at the moment. I've realized that some of the separation between models and views, and their controllers has diminished and I wish to do some cleaning up.

I have several key classes used in my app: NSPersistentDocument, NSWindowController, and a model class.

The NSPersistentDocument class acts as a "model-controller"; it owns an instance of the model class, and manages all interactions with the model.

The NSWindowController class acts as a "view-controller"; it owns the main window, and manages interactions of the views within the main window. This class is also the File's Owner for the nib file in which the Window is defined.

The problem I see here is that I don't have a real "controller". My current design forces the model-controller and view-controller to know about each other. There is no meditating object between the two, and due to this, my model and view are not clearly separated, which makes supporting multiple views or models a problem.

I would like to move functionality from both of my existing controllers into a new "controller" class which would act as a controller between the model-controller and view-controller. In the end, this is still just the MVC design pattern, with just a little more structure.

However, I am having difficulty figuring out how this would fit into Cocoa's document-based app architecture.

The biggest question I have is where and how would this new controller object be created? How does this fit into Cocoa's architecture? Am I fighting against Cocoa's architecture, and is there a better way to do this?


Sounds like you need to pick up a copy of Cocoa Design Patterns, answers these questions and then some.

Chapter 2 deals with the MVC pattern using an ArrayController as the model controller (rather than the persistent document model-controller you are using).

Experienced Objective-C/Cocoa Devs:

What are the key concepts that I should absorb early on that will get me closer to that epiphany moment where it all makes sense and I'm effectively creating solutions with Objective-C/Cocoa? I come from a .NET/Java background so everything I do is based on that paradigm.

I don't need deep specifics but rather the one or two things that you ran into that were different and took a while to soak in. A good example would be when I went from QuickBASIC to C 20+ years ago ... it took me forever to grasp the concept of a pointer. As a result I would say that a key concept of jumping from QuickBASIC to C is to understand memory addressing.

I would recommend Cocoa Design Patterns by Erik M. Buck and Donald A. Yacktman. Excellent book if you want to learn more about Cocoa's key concepts and their background and motivation.

My list:

  • How Cocoa uses the dynamic nature of Objective-C in the implementation of many everyday features like Undo, Bindings, ...
  • Interface Builder is not a code generator.

I am few months old to iphone / ipad development. I know few coding standards, few coding practices. I am not aware of design principles and stuff for building a good iphone application architecture. Guide me with link / books which can help me to do this.

I thought 'Cocoa Design Patterns' by Erik M. Buck was really great.

I need help in understanding MVC model in iPad/iPhone environment. Somehow I can't understand it even after reading several times.

Let's say I want to build a small application that store image location, and the comment for each image. I will possibly create a "SZImage" class that store these information. Aside from setter and getter, do I need to implement other methods? What is the role of model, what methods can it implement and what it can't do?

After that, I will need to setup the interface for displaying image. So I need to create another class with name "SZImageView". What is the role of this class? Does it draw on the iPhone window or I leave it to the controller to do the job. If I leave to the controller to draw, then why should I create this class?

And if I need to have controller to be the bridge between the model and view, then a class with name "SZImageViewController" should be created. What should this class do?

Last, this is the one that have been confusing me for a long time. How can I use the method in other class to add window to the AppDelegate? How does the interaction between instance within class be done. Because I see that the AppDelegate is usually very short and simple.

Model-View-Controller Class Categories and Examples

In Model-View-Controller (MVC), every class should be designed to fit into one of these three categories. In doing so, you can avoid class coupling and create much more flexible code.

Model Classes. Classes of this category should represent the application's data model. If the application is a game then classes that represent the player, enemies, level layouts, saved data (such as scoreboards) and so on. But these classes should be restricted only to holding the data that represents these objects and the logic behind them. For example, if it's a racing game, the class 'Car' should be part of the model, and it should represent all the properties of a car (for example it's speeed, acceleration, turning etc.). This class should also include all the necessary logic for the car, for example logic that determines how the car should move (such as acceleration and breaking, turning), and what should happen in the event of a collison and so on. This 'Car' class should note define how the car is presented to the user. Nor should this class involve any application logic. It should stick completely to describing what it is to be a car.

View Classes. Classes of this category should represent the way in which the application presents the model to the user. Keeping with the previous example, examples of classes that fall into this category would be a 'MainMenu', 'ScoreBoardView', and 'RenderingEngine'. The 'MainMenu' class knows exactly how to display a list of options to the user and how to look really beautiful. It also knows that when one of the options is selected, it should change its visual appearence slightly, such as a button appearing "pushed in". However, this class doesn't know what logic to do when a button is pressed. This is the job of the controller classes. So the view classes simply let the relevant controller know that the user interface has been interacted with by the user (by either calling some controller method or sending a notification out). More on this in the controllers section.

"ScoreboardView" also knows that when it's passed a dictionary (model class) of strings and numbers (player names and scores) that it is to present them in a particular way, perhaps in a table. It doesn't know how to update the dictionary, nor how to calculate the average score. If it want's more information then it needs to ask the controller for it. It's then the controller's job to figure out a way of getting the information.

Finally for this section, a "RenderingEngine" is a view class because it takes a model and produces visuals for it. And that's it. The RenderingEngine is programmed to know how to display a car, and that if the car is set to be in a particular location then it should be drawn in this location, or if the car has collided then it needs to be drawn with buckling. But again, it doesn't know how to update the position of the car, nor the speed and so on.

Controller Classes. Finally, and as I've already previously slightly alluded to, controllers are the classes that bring everything together, and provide the flow and control for your application. People have refered to the controller classes as the "brains" of the application because they make decisions based on the user's input (which is channeled through the view classes) and the data model (which is accessible through the model classes). The controller classes control the application's flow. They take the user from the "main menu" to the "car selection screen" to the "race track" to the "race" to the "scoreboard screen" and so on! They make changes to the model through the classes and they provide the feedback of changes to the view classes so as those classes can present the current state of the application to the user. Controllers effectively link the model and the view together, while at the same providing application logic and program workflow. This program workflow can also include handling issues where the input that is taken from the view does not fit correctly with the model. The view has very little knowledge of the model and can't provide the necessary checks - this is one of the jobs of the controller. For this reason, it's generally considered bad practice to directly link the view classes with the model classes. Of the three types of classes, the controllers are generally the classes that are the least interchangeable, but in practice it is the view and model classes that you would want to interchange the most.

Conclusions. The model-view-controller design pattern allows developers to logically organize their work and the components of their applications. When the model-view-controller paradigm is used it maintains flexibility because any of the three components can be replaced, so long as the replacement module keeps to the same protocol that the other two components expect to be able to intereact with. (When I say "protocol", this can design can either be implemented using inheritence, or for some cases, it's better to use an actual protocol declaration and ensure that classes confirm to the appropriate protocols.) A perfect example of this is that many applications written for the Mac can easily be moved over to iOS because the only major difference between the two platforms is at the user interface level, which is completely understandable given that the interface for the Mac is traditionally a large screen that the user interacts with via a keyboard and a mouse, on the other hand, the interface for iOS consists of a much smaller screen that the user touches to interactive with.

Further reading. The wikipedia page (of course!), MVC in the Apple Developer Documentation, 'Cocoa Design Patterns' by Erik M. Buck.

I've tried to keep this explanation fairly generic to all platforms, frameworks and languages. In iOS development, the MVC design is considered so paramount that you would have to work very hard against the frameworks to avoid using MVC. There is a clear distinction between the view classes (UIView, UITableView, UIAlertView, UIImageView etc.) and the controller classes (UIViewController, UITableViewController, UINavigationController etc.) and the rest of the model classes (NSString, NSDate, NSManagedObjectContext, UIImage etc.). Every class clearly resides in one of these three categories which allows for code reuse and hugely flexibility as you're developing your app.

More specificly relating to your question, your AppDelegate will fall into the controller classes category. It provides the control over the key events of your application. When the application is launched, when it will quit, when it will enter background mode and so on. Your program needs to have a place where the thing to do at these events is handled and this is where it should be implemented.

I hope this helps. I'd also strongly recommend checking out the free WWDC2010 Session Video on the Model-View-Controller paradigm.

I was reading the book "Cocoa Design Pattern" and 2 of its point, in chapter 3 (Two-Stage Creation) are making me confused.

  1. Make sure that the superclass’ Designated Initializer is overridden to call the new Designated Initializer.

  2. When subclassing, make sure every new initializer that isn’t the Designated Initializer calls the Designated Initializer.

My question is how we can call the method for which we don't have the parameters to pass? The book example is being posted below. In this method writer has passed some "static" values, but are we supposed to do this? Or is this always desirable?

My second question is, why I have to override the designated method of super class when I will never call it when I will be initializing my object, other than in my own designated initializer, where I will not be passing any parameters (e.g; in case of NSObject)

@interface MYCircle : NSObject {

NSPoint center;

float   radius; 


// Designated Initializer 

- (id)initWithCenter:(NSPoint)aPoint radius:(float)aRadius;


@implementation MYCircle

// Designated Initializer 

- (id)initWithCenter:(NSPoint)aPoint radius:(float)aRadius {

self = [super init];

if(nil != self) {

center = aPoint;

radius = aRadius; 


return self; 



// Overriden inherited Designated Initializer 
- (id)init {

static const float MYDefaultRadius = 1.0f;

// call Designated Initializer with default arguments

return [self initWithCenter:NSZeroPoint radius:MYDefaultRadius]; 


Please also help me to correct my question because I am not sure what I am really asking is a correct question.


I am developing an app, which is huge project. I need to create an architecture for the app, so that I can reuse the code for another client.(app will be template I will change UI only)

Thinking to apply singleton pattern, but there are some very good design pattern available like MVC, Factory .... Can any one help to find out which is the best design patten I should implement in iPhone app. Or is there any code/tutorial available which explain with examples.

Thanks SD

Also, if you want a good overview of the design patterns underlying Cocoa, I would suggest picking up the book Cocoa Design Patterns by Erik Buck and Donald Yacktman.

I was wondering if anyone would be kind enough to define what a class, instance and method is in Objective-C or point me in the right direction or a good Objective-C learning resource.


For understanding the basic concepts, read the Wikipedia article on OOP.

Once you've understood that, the next step is to read up on Objective-C. For example, there's a nice document from Apple which you should read, and then there's the Objective-C Beginner's Guide. Apart from that, just search on Amazon and pick a book that has good rating/comments and that also covers topics you're interested in, like developing for the iPhone. Most iPhone development books start by giving a (short) introduction to Objective-C.

Once you have gotten your hands dirty with writing some Objective-C code, I recommend reading Cocoa Design Patterns. Do not read it as your first book, but do read it some day ! It explains why the Apple APIs (Cocoa) are the way they are, it explains the concepts and patterns you see in Cocoa. It's not a step-by-step guide but gives an understanding on how things work together.

So I started reading this book:

On chapter 2 it explains about the MVC design pattern and gives and example which I need some clarification to.

The simple example shows a view with the following fields: hourlyRate, WorkHours, Standarthours , salary.

The example is devided into 3 parts : View - contains some text fiels and a table (the table contains a list of employees' data).

Controller - comprised of NSArrayController class (contains an array of MyEmployee)

Model - MyEmployee class which describes an employee. MyEmployee class has one method which return the salary according to the calculation logic, and attributes in accordance with the view UI controls. MyEmployee inherits from NSManagedObject.

Few things i'm not sure of : 1. Inside the MyEmplpyee class implemenation file, the calculation method gets the class attributes using sentence like " [[self valueForKey:@"hourlyRate"] floatValue];" Howevern, inside the header there is no data member named hourlyRate or any of the view fields.

I'm not quite sure how does it work, and how it gets the value from the right view field. (does it have to be the same name as the field name in the view). maybe the conncetion is made somehow using the Interface builder and was not shown in the book ?

and more important: 2. how does it seperate the view from the model ? let's say ,as the book implies might happen, I decide one day to remove one of the fields in the view. as far as I understand, that means changing the way the salary method works in MyEmplpyee (cause we have one field less) , and removing one attribute from the same calss. So how is that separate the View from the Model if changing one reflect on the other ?

I guess I get something wrong... Any comments ? Thanks

  1. The valueForKey: method implementation is discussed here. Note that valueForKey: can actually access the ivars directly without calling any methods.

  2. If you remove a column from your NSTableView you don't have to remove it from your model object class. It's still there, it just doesn't get displayed.

I have the following code that I am calling using this statement: SQLiteDB *db = [[[SQLiteDB alloc] init] autorelease];

The problem is "sharedSQLiteDB" is not being called, but rather "allocWithZone" is, and therefore "checkIfDatabaseExists" is not being called, which is where the database is created.

I don't understand why... (i.e. what am I doing wrong?)

#import "SQLiteDB.h"

static SQLiteDB *sharedSQLiteDB = nil;  //  makes this a singleton class

@implementation SQLiteDB

@synthesize searchPaths, documentPath, databasePath, cDatabasePath;

#pragma mark Singleton Methods

+ (SQLiteDB *) sharedSQLiteDB  {

    if(!sharedSQLiteDB)  {
        sharedSQLiteDB = [[SQLiteDB alloc] init];
        [sharedSQLiteDB checkIfDatabaseExists];  //  check to see if d/b exists
    return sharedSQLiteDB;

+(id)allocWithZone:(NSZone *)zone  {  //  makes sure another instance is not allocated
    if(!sharedSQLiteDB)  {
        sharedSQLiteDB = [super allocWithZone:zone];
        return  sharedSQLiteDB;
    else {
        return nil;

-(id)copyWithZone:(NSZone *)zone  {
    return self;

-(void) release  {
    //  no-op

In the singleton pattern your use pattern should be:

SQLiteDB* db = [SQLiteDB sharedSQLiteDB];

They way you are calling it doesn't fit the singelton pattern. All access should be through your sharedSQLiteDB message.

In other words you shouldn't be initializing via typical Cocoa patterns (SQLiteDB *db = [[[SQLiteDB alloc] init] autorelease]; is incorrect and full of problems) outside the scope of the class.

In a singleton using the default initialization pattern for the language (alloc/init for ObjC or the default constructor for C++) should generate a compile time error message since the constructor/init method should be protected.

See the Wikipedia entry. consult the Design Pattern C++ bible. There is even a version for Cocoa

Good luck.

I'm writing an iPhone application in Objective-C. I created a class (Foo.m) which I would like to be able to call a method in the controller (MainViewController.m) which instantiated it. How do I do this? Please provide an example. Thank you!

You should probably check out Cocoa Design Patterns by Erik M. Buck and Donald A. Yacktman. It's an amazingly excellent book and it's quite comprehensible even if you aren't already familiar with design patterns in general.

It sounds like what you want to do is what the other guys were saying which is a pattern called Delegation. To see how delegation works, look at all of the built in classes that use it. Anything that has a delegate property and a protocol like UIBlablaDelegate is using delegation and you can do the same thing with your classes.

Is there a good tutorial/book/site that addresses general questions about structuring your iOS app code? Common patterns, best practices, etc. Questions like where does one put webservice or database access code, what the best way to do login/authentication, etc.

Thank you

I recommend Cocoa Design Patterns. While not specific to iOS programming, it will teach you a lot about patterns used in Cocoa (Touch included) and will probably answer a lot of your questions.

I've heared about singletons and categorys throughout my search for a way to pass data from one view and back using a navigation controller.

Ive also found the segue method but that's just a one-way

So my question is: Are there any good tutorials or a capital in a book that can teach me the basics and maybe advanced techniques of categorys and singletons? Like what it is / how it works / neat stuff to do with it.

Couldn't find anything anywhere I'm afraid. :'(

I'm a big fan of Cocoa Design Patterns. Great coverage of categories, singletons, and many more topics.

Yes I've seen questions like these before but they're all for people who basically want to start from scratch. I come from AppleScript Studio (for those who do not know it, it's AppleScript in Xcode with IB etc.). The only things new to me are related to interface and implementation files. In my code I've already written 2000+ lines of ObjC, so it's not the syntax. But I fail to understand inheritance, accessing variables from other class files, etc.. The way I use ObjC is having one NSObject in IB which its class is changed to something new by me and then all my code is written in that one implementation file. My biggest problem is finding out how to access parameters from other classes.

So do any of you have any tips on where to start? Normally I'd start from scratch with a book but I seem to fairly be able to write code as long as it's located in one big file...

Thanks for your help.

Although you understand Interface Builder, it's very clear that you don't understand Objective-C or Cocoa very well at all. You need to stop flailing around and give yourself a firm grounding in the language and frameworks. The only way to do this properly is to start at the beginning.

You should start by learning Objective-C properly. In my opinion, the best way to to this is to read Stephen Kochan's superb Programming in Objective-C 2.0. This will teach you how to write Objective-C properly and explain object-oriented coding, class inheritance and so on. You should read the book cover to cover and do all the exercises.

You should then read Aaron Hillegass' Cocoa Programming for Mac OS X which will teach you how to take Objective-C and marry it to Interface Builder and the Cocoa frameworks to produce working Cocoa apps.

You should also read Cocoa Design Patterns which will explain what the design patterns in Cocoa are and how to use them to your advantage to write Cocoa apps the right way.

which is the best design pattern in objective c?

please specify useful links to see before we go to dive to code!!!!!

because everytime while i go to dive straight to code i confused at middle of some point.To clear this we have to make first design then we can implement them.

please specify any useful links.

Design patterns are many and no one is the best. They typically solve different problems in different domains. You can check out the book Cocoa Design Patterns, it should provide enough text and code to help you choose which pattern you need to use for your problems. :-)