Can you help me understand what Cocoa is? - iphone

I have spent a lot of time getting into iOS development. I have spent a lot of time familiarizing myself with objective-c as well as xcode. I have spent a lot of time going through the motions without understanding the fundamentals of what Cocoa is.
I haven't grown up my entire life understanding coding concepts as some people have, and when people tell me that Cocoa is a framework, that doesn't really mean very much to me.
Can somebody undertake to explain IN SIMPLE ENGLISH what Cocoa is? What a framework is? How I as an aspiring developer should use it? What it should mean to me? I have spent so much time trying to understand it from definitions that don't make sense, that I wanted to try this and see if something could just click.
Thanks for your time

Think of a framework like a library. So let's talk in terms of books. A library is full of books! In this case, our books are our classes. Now books have pages that tell the story, and classes do too, they're called methods and properties.
So based on the above, we can tell that libraries contain classes which help us do things. A framework is just a packaged library really.
When you write things like:
NSObject* foo = [[NSObject alloc] init];
and later call:
[foo release];
what you're doing is using parts of Cocoa—specifically, memory management. +alloc is a class method which creates an object, and -init is an instance method (+ refers to class methods, - refers to instance methods—that's how they get defined in Objective-C code). Likewise, -release is used to release your ownership of the object you created previous.
These three methods are part of Cocoa. In the NSObject book.
I hope this is simple enough for you to understand.

In addition to containing library routines, a framework usually forces your application into a certain paradigm, such as requiring your app to be structured in a certain way, and/or requiring a lot of defined subroutines/methods in your app that the framework can call. In fact, a framework such a Cocoa Touch can often call your app far more than your app might call any library code in the framework.
One good way of learning a framework is to read the source code of many example apps, and try to separate out the application logic from the framework glue.

Related

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 are the key concepts for an iPhone Developer to learn? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
I'm new to Objective-C and I have gone through many topics, What are the key concepts on which I should put more emphasis for developing iPhone Apps?
There are a number of concepts which make up the basics of iOS development. There coding patterns, techniques and some general tidbits that you should know about.
Coding Patterns:
Key Value Observing (KVO): Allowing one object to respond to changes of another object's properties by registering the "Observer" with the "target" object. For more on KVO, see Apple's Key-Value Observing Programming Guide.
Model View Controller Pattern: In the Model View Controller Pattern (MVC) objects generally fit into one of three roles. You have the Model, which is, at the most basic level, your data. (Or, more accurately, how the data is structured.) You have the View, which is what the user sees on the screen. Lastly, you have the Controller, which coordinates between the the model and the view. The controller is where your business logic usually goes. Apple has documentation on MVC as well.
The Singleton Pattern: Singleton classes (that's an oxymoron, "singleton classes") are classes which can only have one instance of them in an application at a time. Singletons are good for "factory classes", or objects that you won't want two of. The UIDevice class, for example, is a singleton class. (Your iPhone isn't an iPad and an iPhone at the same time, now is it?) In the iOS SDK, singleton classes often have a special initializer. Instead of the usual [[Class alloc] init], singletons often use [SingletonClass sharedInstance]. ("shared"Instance, since the instance is "shared" across your application.) Note that Singleton classes work a little differently in regards to memory management.
Coding Techniques:
Delegation: Many objects in the iOS SDK have delegate objects, that respond to certain "events" of the object that they are "delegating" for. For example, you could have a UIPickerView (a scrolling wheel with a bunch of choices on it). When the user chooses a date, the delegate, ( a different object than the UIPickerView) will implement – pickerView:didSelectRow:inComponent:, which will allow that object to do something in response to the action.
Memory Management: Unlike many languages, be it Java, Javascript, or anything in between usually manage memory for you. On iOS, Objective-C does not do this. You need to keep track of all of your objects and release them when you are finished with them. The rule of thumb is that for every alloc, retain, new, and copy, you must have a corresponding release, or autorelease. (A note about autorelease: People often have trouble with understanding autorelease. Generally speaking, local "autoreleased" objects are guaranteed to be around until the end of method call. No more, no less. Of course, if you retain the object elsewhere, it will still have a reference from that point.)
ARC: With the iOS 5 SDK, Apple introduced Automatic Reference Counting. It's important to understand the basics of how this works, even if you plan on working with manual reference counting. You never know when you'll run into ARCified code that you'll need to work with.
Data Persistence: Many folks who are getting started also have a challenge with saving data in between launches. You have three options, depending on the type of data. You can use NSUserDefaults, the Documents Directory (or one of a few other folders in your App's directory hierarchy, or Core Data. You also use these in conjunction with each other, as they are not mutually exclusive.
Basic Concepts:
IBOutlets and IBActions: IBAction and IBOutlet are typedefs for void. IBAction methods return void and are marked as IBAction so that Interface Builder can allow you to attach them to objects in your NIB files. IBOutlets are "placeholders" in code that are used to allow you to set properties, or otherwise interact with objects in your NIB files via Objective-C code.
The # symbol: The # symbol represents Objective-C constants, since Objective-C is a superset or Framework on top of C. In C, a string constant would be "My string is cool.". In Objective-C it would be #"My string is cooler in Objective-C." Other examples of the # symbol being used to distinguish between C and Objective-C are keywords like #implementation, #property, #class and #end.
Pointers: Dave DeLong explains this in his answer, but this is something else to make sure you know as well.
Finally, I leave you with a word of advice:
Although you have StackOverflow, and it really is a wonderful resource, know how to use the Apple Documentation. Enjoy your journey and good luck Getting Started!
Good luck!
These aren't necessarily specific to iPhone development, but without them, you will not ever get it.
Pointers - know what a pointer is. Know why we need the dynamically allocated memory versus statically allocated memory. (I know this may sound trivial, but in my experience, this is the #1 thing that newcomers have the most trouble with) This is because you'll never* deal with raw objects in Objective-C. You always deal with object references. (ie, you never deal with an NSString, but always an NSString *) However, there are things that look like objects, but aren't actually. NSRects are structs and they can be stack-allocated. NSInteger is simply a typedef for a primitive int. If you don't know what a pointer is, you'll go crazy wondering when you're supposed to put in a * and when you're not.
Memory Management - the iPhone does not have garbage collection. You must manually manage your memory. Accept that and move on. The rules for memory management conventions in Objective-C are trivial. Memorize them, and always remember to use them.
* the only time you'll deal with stack-allocated objects are blocks (^{ ... }) or when you're doing something fiendishly devious.
For developing successful iPhone apps, you need to know more than the typically offered Objective C best practices. Of Objective C practices, knowing the delegation pattern and memory management rules is very important for iPhone development.
There are lots and lots of APIs in the Cocoa Touch framework. The more APIs you are familiar with, and have played with, the better. That alone can take a significant amount of time.
You should learn that an event driven framework such as Cocoa Touch mostly calls your app, not vice versa.
You should learn how UI design works differently on touch based devices with tiny displays. Too few developers see if their grandma (et.al.) wearing thick tri-focals can even see some of their icons. Or whether a UI control can be operated while using a device one-handed while walking around. Etc.
You should learn how to design for constrained system. A mobile device likely does not have seemingly infinite amount of backing swap memory. So you need to learn how to measure and strongly control an app's memory footprint. And the battery on a small device will last a lot longer if your apps can leave the CPU mostly idle. So you will want to learn how to profile your algorithms and how to pick efficient ones.
I suggest getting an older slower iOS device, and learning how to make apps work well under those limitations first. (I've heard that Apple used to do that internally as part of their training.)

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.

iOS Application partitioning / MVC

I've been playing around with iOS development and I'm getting to the stage where I want to create something beyond a simple app. However, I'm not confident that I understand how to partition an application correctly.
For the purposes of simplicity, imagine a (very) simple audio player application. Let's say there are two view controllers, accessible via a UITabBarController which is instantiated the main AppDelegate class.
Each of these view controllers has the following responsibility:
PlayerViewController - A sound player which plays the “current” audio sample when the user presses a button.
SelectorViewController - A sample selector, that uses a UIPickerView to display the available audio samples so that the user can select which sample they want to play.
So far, so good. However, what I don't quite understand is where I should store the data on the available samples, so that both of the views can find out information on the available samples, trigger a sample to play, etc.
As both view controllers need to access this “model level” information, would creating an “audio manager” singleton class be a sensible approach, or is there (much, much more likely I'm guessing) a better means of solving this problem that I'm overlooking.
Any pointers would be much appreciated.
I've used this pattern (Singleton data manager) several times in serious apps. It's quite straightforward, easy to understand, easy to use, although this pattern is despised by OOP purists.
If nobody tells you it's wrong to use a singleton, go ahead, just be sure to check Apple's documentation on the recommended implementation (there is a bunch of methods to overload).
Oh and BTW, Apple uses it a lot in the iOS SDK, so it's a common practice (see class methods beginning with 'shared').
UPDATE:
Another possibility is reusing an already existing singleton, the Application delegate for instance. It might feel cleaner, or not, it's more a matter of taste. It has the advantage of giving a clear "entry point" where you allocate/create/init your data manager.
If the source of your data is in a remote server and it comes to your app as an XML file, you can also get it whenever you want with a kind of source downloader class.
That way you don't have to care about keeping things in memory when they are not necessary. Just get it from the remote source, parse it and then release it.
Another way of achieving this more careful use of memory is to get your data from a sqlite database using Core Data. But some people thinks it is too much complicated for a simple app and prefer running queries by hand.

Is there a preferred method of database management/object persistence on the iPhone?

I've seen several approaches, and each seem to have significant plusses and minuses. I'm learning iPhone development, I'm building a relatively simple app, which, at it's core, is really not much more than CRUD operations on 3 or four related entities.
I'm used to ActiveRecord-type object persistence. The implementations for Cocoa Touch that I read about online are commonly referred to as extremely slow.
Most of the examples I see online (specifically the Pragmatic Programmers screencasts) have SQL hardcoded into the controller class, which doesn't seem... right to me. Seems very old school (but maybe old school is best in this case).
I know we can't discuss SDK 3.0 here, but it's common knowledge that CoreData is coming for the iPhone, that would of course limit my audience (I'm not sure I really care about that this much. It will be an app for sale, but I'm not planning on it replacing my career)
I have not tried Gus Mueller's FMDB yet, but I have read good things.
What are some of your experiences, what works, and what doesn't. Where would you recommend that a (still pretty novice) iPhone programmer invest their time?
Right now there's a lot of semi-raw SQL encoded in apps because there's no built-in system for higher level work. FMDB is a nice way to do this but it just wraps the SQLite calls into something more Objective-C like. It's great for some situations but obviously not for everything.
If you're familiar with ActiveRecord then SQLite Persistent Objects may be useful to you, because it's intended to be similar to ActiveRecord. I haven't used either so I couldn't tell you how similar it actually is. If that doesn't seem right for some reason, it's probably best at this point to target 3.0 and make use of Core Data.