Cocoa touch connection and data design pattern - iphone

My question is a design issue and it has been driving crazy over the last couple of days. I am new to cocoa touch development.
I have an application that has a UINavigarion controller and a 3 views. I need to keep communicate with a WCF service and store the data on the app side.
How do I create my Model (MVC) in a way that makes the data available to all controllers?
What I started doing is a singleton that handles all the storage and web calls but I read thru the threads that it is a bad idea. I also considered putting the code in the appDelegate but people say that is a bad idea too.
Conceptually how would u design your model and communicate with the controllers?
Any help is much appreciated.

You will get different advice because opinions differ on the best method to use. As you noted, for handling a data model, there are two major design patterns: Dependency Injection and Singleton.
Dependency Injection relies on passing the data model object from view controller to view controller as needed. Marcus Zarra (author of Core Data: Apple's API for Persisting Data on Mac OS X which I recommend) wrote a good article explaining Dependency Injection. Most of the Apple documentation recommends that you use the Dependency Injection design.
I like the Singleton pattern but it is very, very, very dangerous for a novice to use. The Singleton pattern is so easy to do wrong that most graybeards have given up on it and simply advise novices to never use it.
The Singleton pattern has the advantage of increasing modularity and flexibility of the app. However, it requires that you have a firm idea of what the data model will do before you start coding both the Data Model and the UI. It requires more work up front to get correct and it is not as forgiving as Dependency Injection. You have to use singletons with greater discipline.
For a simple app with three hierarchal views, Dependency Injection is the simplest and cleanest design to implement. You won't need the flexibility of a singleton and a singleton will just add unneeded complexity. The Navigation-based template with Core Data provided by Xcode will give you 50% of the app to start. Just add the second and third tier views and you're done.

Related

MVC in Cocoa Touch

I'm having troubles understanding if I'm properly implementing the MVC pattern in an iPhone app. In my app I have views, view controllers and models. The view controllers manage the interfaces, navigate to other view controllers, set variables to other view controllers and models, and communicate with the models. But this way, am I correctly following the MVC pattern? Don't I miss a model controller?
Another question: I have a User Model that I need to have access to in almost every models and some controllers. Would it be correct to define it as a variable in the appDelegate? I'm all the time reading that this is a bad practice, but I don't see why in this case.
Global objects
All non trivial code has bugs, and they are harder to track if you use dumb global objects. By "dumb" I mean generic objects from the API that lack a single point of access in case you need to log, validate, key-value observe, and notify, changes. You can wrap the global object in a class to route everything through your own accessors.
Some say using globals at all gets you into a bad habit. Others say it depends on the size of your code because it is a trade between development speed and complexity.
The appdelegate is a Singleton, so this discussion is related: What is so bad about singletons? and Singletons: good design or a crutch?.
MVC
Apple talks about it in Cocoa Core Competencies and Cocoa Fundamentals Guide.
One can merge the MVC roles played by
an object, making an object, for
example, fulfill both the controller
and view roles—in which case, it would
be called a view controller. In the
same way, you can also have
model-controller objects. For some
applications, combining roles like
this is an acceptable design.
Is your design complex enough to need a model controller? Whatever your decission is, suffering the consequences will teach you a lot. :)
A design pattern in which the model (any data in your program), the view (what the user sees), and the controller (a layer that handles all interaction between the view and model) are separated in such a manner that modifying either the view or model component of your program has no effect on one another.
The purpose:
The purpose is that later on you may need to change your programs view, and by programming things in this matter you will not have to modify your programs model. Say for instance Apple comes out with an iPad for which the view is programmed somewhat differently than on the iPhone, but you would like to
Now I received some messages after making the video above, some thanking me for making the concept of MVC sound so simple, and others telling me that I had confused them, and wondering how I could understand any of this stuff.
Well, don’t fret.. I’ve seen arguments all over the place as to what components should be classified in the model, the view, or the controller, and I’ve even seen accomplished "guru authors" mess things up when explaining what goes where, just keep in mind that the key idea here is that you can modify one of these key areas without completely wrecking another key area of your program, and leave the rants to the wannabe coders who like to argue about what exactly what fits what acronym, and MVC is often their target.

Alternative to Singleton in Objective-C for better application design

It seems a lot of Objective-C code is using Singleton nowadays.
While a lot of people complaining about Singleton, e.g. Google (Where Have All the Singletons Gone?), their fellow engineers also use it anyway: http://code.google.com/mobile/analytics/docs/iphone/
I know we had some answers in Stack Overflow already but they are not totally specific to Objective-C as a dynamic language: Objective C has categories, while many other languages do not.
So what is your opinion? Do you still use Singleton? If so, how do you make your app more testable?
Updated: I think we need to use codes as example for more concrete discussion, so much discussions on SO are theory based without a single line of code
Let's use the Google Analytics iOS SDK as an example:
// Initialization
[[GANTracker sharedTracker] startTrackerWithAccountID:#"UA-0000000-1"
dispatchPeriod:kGANDispatchPeriodSec
delegate:nil];
// Track page view
[[GANTracker sharedTracker] trackPageview:#"/app_entry_point"
withError:&error];
The beauty of the above code is once you have initialized using the method "startTrackerWithAccountID", you can run method "trackPageview" throughout out your apps without passing through configurations.
If you think Singleton is bad, can you improve the above code?
Much thanked for your input, have a happy Friday.
This post is likely to be downvote-bait, but I don't really understand why singletons get no love. They're perfectly valid, you just have to understand what they're useful for.
In iOS development, you have one and only one instance of the application you currently are. You're only one application, right? You're not two or zero applications, are you? So the framework provides you with a UIApplication singleton through which to get at application-level os and framework features. It models something appropriately to have that be a singleton.
If you've got data fields of which there can and should be only one, and you need to get to them from all over the place in your app, there's totally nothing wrong with modeling that as a singleton too. Creating a singleton as a globals bucket is probably a misuse of the pattern, and I think that's probably what most people object to about them. But if you're modeling something that has "singleness" to it, a singleton might well be the way to go.
Some developers seem to have a fundamental disgust for singletons, but when actually asked why, they mumble something about globals and namespaces and aesthetics. Which I guess I can understand, if you've really resolved once and for all that Singletons are an anti-pattern and to be abhorred in all cases. But you're not thinking anymore, at that point. And the framework design disagrees with you.
I think most developers go through the Singleton phase, where you have everything you need at your fingertips, in a bunch of wonderful Singletons.
Then you discover that unit testing with Singletons can be difficult. You don't actually want to connect to the database, but your Singleton does. Add a layer of redirection and mock it.
Then you discover that unit testing isn't the only time you need different behaviour. You make your Singleton configurable to have different behaviour based on a parameter. You start to wonder if you need to split it into two Singletons. Then your code needs to know which Singleton to use, so you need a Singleton that knows which Singleton to use.
Then some other code starts messing with the values in your Singleton, while you're using it. How dare they! If you wanted just anybody to get at those values from anywhere, you'd make them global...
Once you get to this point, you start wondering if Singletons were the right solution. You start to see the dangers of global data, particularly within an OO design, where you just assume your data won't get poked at by other people.
So you go back and start passing the data along, rather than looking it up (this used to be called good OO design, but now it has a fancy name like "Dependency Injection").
Eventually you learn that Singletons are fine in moderation. You learn to recognize when your Singleton needs to stop being single.
So you get shared objects like UIApplication and NSUserDefaults. Those are good uses of Singletons.
I got burned enough in the Java Singleton craze a decade ago. I don't even consider writing my own Singletons. The only time I've needed anything similar in recent memory is wanting to cache the result of [NSCalendar currentCalendar] (which takes a long time). I created a category on NSCalendar and cached it as a static variable. I felt a bit dirty, but the alternative was painfully slow code.
To summarize and for those who tl;dr:
Singletons are a tool. They're not likely to be the right tool, but you have to discover that for yourself.
Why do you need an answer that is "total Objective C specific"? Singletons aren't totally Obj-C specific either, and you're able to use those. Functions aren't Obj-C-specific, integers aren't Obj-C specific, and yet you're able to use all of those in your Obj-C code.
The obvious replacements for a singleton work in any language.
A singleton is a badly-designed global.
So the simplest replacement is to just make it a regular global, without the silly "one instance only" restriction.
A more thorough solution is, instead of having a globally accessible object at all, pass it as a parameter to the functions that need it.
And finally, you can go for a hybrid solution using a Dependency Injection framework.
The problem with singletons is that they can lead to tight coupling. Let's say you're building an airline booking system: your booking controller might use an
id<FlightsClient>
A common way to obtain it within the controller would be as follows:
_flightsClient = [FlightsClient sharedInstance];
Drawbacks:
It becomes difficult to test a class in isolation.
If you want to change the flight client for another implementation, its necessary to search through the application and swap it out one by one.
If there's a case where the application should use a different implementation (eg OnlineFlightClient, OfflineFlightClient), things get tricky.
A good workaround is to apply the dependency injection design pattern.
Think of dependency injectionas telling an architectural story. When the key actors in your application are pulled up into an assembly, then the application’s configuration is correctly modularized (removing duplication). Having created this script, its now easy to reconfigure or swap one actor for another.”. In this way we need not understand all of a problem at once, its easy to evolve our app’s design as the requirements evolve.
Here's a dependency injection library: https://github.com/typhoon-framework/Typhoon

what is best approach of accessing data around all classes and handling it in iphone programming?

I developed an application for iphone, and made all my setters and getter, and handled sqlite3 database (select, insert, delete, update) in AppDelegate.m
I made AppDelegate Object and used all around my application, I felt that my application started to give strange errors, and heaviness, crash.
then I made another class as DataManagement, then I used it and rotate objects, now there is no error, nothing like crash,,,,
I want to know from you seniours that what is best way to handle getters and setters and database in iphone programming?
any other good way, so that application became now too much heavy at all,,,,
Reading about the Model-View-Controller pattern is a good starting point when learning about application design.
Apple provides a really good document in it's "Cocoa Core Competencies" series:
http://developer.apple.com/library/ios/#documentation/general/conceptual/DevPedia-CocoaCore/MVC.html
A general MVC description can be found in Wikipedia:
http://en.wikipedia.org/wiki/Model–view–controller
I'm sorry for being a bit harsh here, but it appears like you've not yet understood the basic concept of object oriented programming, if initially you tried to implement a whole application within your application delegate.
I don't think that telling you how to create accessors or how to use Core Data (I believe this is what you meant) will help you unless you've spend some time reading through some of the basics (although accessors are a part of the basic stuff).
As a start, I'd like to recommend reading this Guide about the Objective-C language and going through some basic tutorials and example projects.

Need some advice on starting a New Life with MVC 2 and which Tools to use for RAD in MVC2?

I have finally decided to hop up on the train of MVC 2.
Now I have been doing a lot of reading lately and following is the architecture which I think will be good enough for most Business Web Applications.
Layered Architecture:-
Model (layer which communicates with Database). EF4
Repository (Layer which communicates with Model and includes all the queries)
Business Layer (Validations, Helper Functions, Calls to repository)
Controllers (Controls the flow of the application and is responsible for providing data to the view from the Business Layer.)
Views (UI)
Now I have decided to create a separate project for each layer (Just to respect the separation of concerns dilemma. Although I know it's not necessary but I think it makes the project look more professional :-)
I am using AutoMetaData t4 template for Validation. I also came across FluentValidation but cant find much on it. Which one should I go with?
Which View Engine to go for?
Razor View Engine Was Love at first sight. But it's still in beta and I think it won't be easy to find examples of it. Am I right?
Spark .. I can't find much on it either and don't want to get stuck somewhere in the middle crying for help when there is no one to listen...:-(
T4 templates auto generate views and I can customize them to generate the views the way I want? Will this be possible with razor and spark or do I have to create them manually?
Is there any way to Auto generate the repositories?
I would really appreciate it if I can see a project based on the architecture above.
Kindly to let me know if it's a good architecture to follow.
I have some confusion on the business layer like is it really necessary?
This is a very broad question. I decided to use Fluent NHibernate's autoconfig feature for a greenfield application, and was quite impressed. A lot of my colleagues use CakePHP, and it needed very little configuration to get it to generate a database schema compatible with the default conventions cake uses, which is great for us.
I highly suggest the book ASP.NET MVC2 in Action. This book does a good job at covering the ecosystem of libraries that are used in making a maintainable ASP.NET MVC application.
As for the choice of view engines, that can depend on your background. I personally prefer my view to look as much like the HTML as possible, so I would choose Spark. On the other hand if you are used to working with ASP.NET classic, the WebForms view engine may get you up and running fastest.
Kindly to let me know if its a good architecture to follow?
It's a fine start - the only thing I would suggest you add is a layer of abstraction between your Business Logic and Data Access (i.e: Dependency Inversion / Injection) - see this: An Introduction to Dependency Inversion.
i know its not necessary but i think it makes the project looks more professional :-)
Ha! Usually you'll find that a lot of "stuff" isn't necessary - right up until the moment when it is, at which point it's usually too late.
Re View Engines: I'm still a newbie to ASP.NET MVC myself and so aren't familiar with the view engines your talking about; if I were you I'd dream up some test scenarios and then try tackling them with each product so you can directly compare them. Often, you need to take things for a test drive to be more comfortable - although this might take time, but it's usually worth it.
Edit:
If i suggest this layer to my PM and give him the above two reasons then i don't think he will accept it
Firstly, PM's are not tech leads (usually); you have responsibility for the design of the solution - not the PM. This isn't uncommon, in my experience most of the time the PM isn't even aware they are encroaching on your turf that isn't theres. It's not that I'm a "political land grabber" but I just tend to think of "separation of concerns" and, well, I'm sure you understand.
As the designer / architect it's up to you to interpret requirements and (taking business priorities into account) come up with solution that provides the best 'platform' going forward.
(Regarding DI) My question is , is it really worth it?
If you put a gun to my head I would say yes, however the real world is a little more complex.
If you answer yes to any of these questions then its more likely using DI would be a good idea:
The system is non-trivial
The expected life of the system is more than (not sure what the right figure is here, there probably isn't one, so I'm going to put a stake in the ground at) 2 years.
The system and/or its requirements are fluid.
Splitting up the work (BL / DAL) into different teams would be advantageous to the project (perhaps you're part of a distributed team).
The system is intended for a market with a diverse technical landscape (e.g: not everyone will want to use MS SQL).
You want to perform quality testing (this would make it easier).
The system is large / complex, so splitting up functionality and putting it into other systems is a possibility.
You want to offer more than one way to store data (say a file based repository for free, and a database driven repository for a fee).
Business drivers / environment are volatile - what if they came to you and said "this is excellent but now we want to offer a cloud-based version, can you put it on Azure?"
Id also like to point out that whilst there's definitely a learning curve involved it's not that huge, and once you're up-to-speed you'll still be at least as fast as you are now; or at worst you;ll take a little longer but you'll be providing much more value (with relatively less effort).
In terms of how much effort is involved...
One-Off Tasks (beyond getting the team up to speed):
Writting a Provider Loader or picking DI Framework. Once you've done this it will be reusable in all your projects.
'New' Common Tasks (assuming you're following the approach taken in the article):
Defining interface (on paper) - this is something you'll be doing right now anyway, except that you might not realise it. Basically it's OO Design, but as it's going to be the formal interface between two or more packages you need to give it some thought (and yes you can still refactor it - but ideally the interface should be "stable" and not change a lot; if it does change it's better to 'add' than to 'remove or change' existing members).
Writting interface code. This is very fast (minutes not hours), as you're not writting any implementation; and when you go to implement you can use tools provided by your IDE to generate code-stubs based on the interface.
Things you do now that you'd do differently:
Instantiating a variable (in your BL classes) to hold the provider, probably via a factory. Writting this shouldn't take long (again, minutes not hours) and it's fairly simple code to copy, paste & refactor where required.
Writing the DAL code: should be the same as before.
Sometimes it is way more easy to learn patterns from code : Sharp Architecture is a concrete implementation of good practices in MVC, using DDD.

Whis is the best technical architcture for iPhone app?

I am developing an app, which is a 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, etc. How can I 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.
The iPhone is completely geared toward MVC, so that one's a no-brainer. Don't try to use another pattern to organize your app - it'll just become a hacked up mess. As far as other patterns go, Singleton is always a good one. If you make singleton objects that manage common behaviors (networking, for example), you can reuse them in other projects pretty easily.
Custom views are also easy to re-use. If you create a custom UIView subclass for part of your UI and define Objective-C protocols for it's data source and delegate interactions (the points where it is tied into your controller and model), you should be able to take them with you to future projects.
Also consider using Core Data to store the "Model" part of your MVC app. Core Data is an ORM that is built into the iPhone platform. It allows you to store everything in an SQLLite database while working with Objective-C objects in your code. It's really handy if you're creating lots of apps with the same data or with the same UI but different data. (aka all those "fans of XYZ" apps!)
That's such a vague question that the only possible answer is "a good one."
You already have a choice of templates when you start a new iPhone app in Xcode. Those suggest architectures...
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.