Programming in Objective-C

Stephen G. Kochan

Mentioned 12

Presents an introduction to Objective-C, covering such topics as classes and objects, data types, polymorphism, Foundation Framework, memory management, and archiving.

More on Amazon.com

Mentioned in questions and answers.

Being an aspiring Apple developer, I want to get the opinions of the community if it is better to learn C first before moving into Objective-C and ultimately the Cocoa Framework?

My gut says learn C, which will give me a good foundation.

You can readily enough learn C and Objective-C at the same time -- there's certainly no need to learn the minutiae of C (including pointer arithmetic and so on) before starting with Objective-C's additions to the language, and as a novice programmer getting underway with Objective-C quickly may help you to start "thinking in objects" more quickly.

In terms of available resources, Apple's documentation does typically assume familiarity with C, so starting with The Objective-C 2.0 Programming Language won't be of much benefit to you. I would invest in a copy of Programming in Objective-C by Stephen Kochan (depending on how quickly you want to get underway, you may consider waiting for the second edition):

Programming Objective-C Developers Library Programming Objective-C 2.0 Developers Library

It assumes no prior experience, and teaches you Objective-C and as much C as you need.

If you're feeling a little ambitious, you might start with Scott Stevenson's "Learn C" Tutorial, but it does have some prerequisites ("You should already know at least one scripting or programming language, including functions, variables and loops. You'll also need to type commands into the Mac OS X Terminal.").

(Just for the record and for context: I learned both at the same time back in 1991 -- it didn't seem to do me any harm. I did, though, have a background in BASIC, Pascal, Logo, and LISP.)

Do you want to be a hard-core developer? Then learn c first.

The books you need to completely master c are some of the best writings in technology. Here's what you need:

C Programming Language

The Standard C Library

I'm a self-taught programmer who jumped into Python as my first language about 7-8 months ago. I'm fairly solid at making things work, though my foundational knowledge is limited thanks to my questionable choice in college to not study computer science.

Beyond Python, I'm not really familiar with C or other lower level languages.

I would like to teach myself Objective C as a foray into programming iPhone apps (as a hobby initially). I initially want to create relatively simple utility apps (I think they are relatively simple, at least).

Could any one give me a guess as to how long it might take me to pick up Objective C and actually produce a semi-decent app? If time is of the essence, should I just scrap it and go with HTML5?

I pick things up fairly fast but, again, my background in Comp Sci is really limited.

Sorry if this question is a bit too general and thanks for any insight!

I had to learn objective-C a couple of months ago to make an app for an internship. I had experience with C/C++, and learning Obj-C wasn't difficult at all. What was difficult was learning to use the SDK. Granted, I had next to no experience with using something like it before, but it was a significant learning curve to get a handle on actually putting the app together using Apple's tools. If you're in the same boat, that's something that will probably add to the time it takes to produce a finished app. (I finished the app in about a month.)

I agree with other posters that there are some great Stanford tutorials on iTunes, but as a reference I found Kochan's Programming in Objective-C very valuable. He states in the intro that he does not expect prior C knowledge from readers, and doesn't think it's necessary -- might be a good book for your situation.

Depending on the complexity of the app you want to build, I think you could build something decent in a month or two.

I'm primarily a designer, with a fairly high level of understanding of CSS and HTML. I have an idea for a very simple iPhone app, largely involving a timer, an animated graphic, and some sound. If I get more advanced there could be some simple customization settings

I have no understanding of Objective C, or C of any kind for that matter. (The closest I got was a Pascal course 20 years ago.) Aside from befriending a developer with motivation to help me out, what would be the simplest, most likely method of learning the minimum I need to know to create my own iPhone App?

If you're really serious about it and are willing to put in some time to actually learn to program in Cocoa, the way I would do it would be a combination of reading all the stuff Apple has to offer along with a couple good books both for reference and more conceptual big picture/getting into the Cocoa mindset stuff.

If you just want to try to hack something together that works than you'll probably do best with a combination of Apple's sample code and lots of questions on various forums when you get stuck.

The books I would recommend would be Programming in Objective-C, by Stephen Kochan and Cocoa Programming for Mac OS X, by Aaron Hillegass. The former is a good introduction to the Objective-C language itself, and the latter is pretty much the Cocoa book. It's not an iPhone specific book, but pretty much everything in it (especially the concepts and design patterns) still apply. Keep in mind you wont have access to the garbage collector on the iPhone. You should also be sure to read through Apple's own Introduction to The Objective-C 2.0 Programming Language.

For actual code to look over and adapt to your own needs, it's hard to find anything better than Apple's own iPhone sample code library.

You might also try these two forums for any SDK questions you might have, as well as of course Stack Overflow for the more general stuff that doesn't fall under the NDA.

I'm very keen to learn Iphone apps development. Can you experts give me some tips as to which programing tool I should learn? tools I should install [of course , I prefer free tools]?, operating system I need? [I only have windows xp and unix flavours on my Personal laptop]. Do I need to have Iphone to test my apps? [poor guy, I don't own a Iphone].

Thanks to all who responded , every message seems very informative and useful (+1 to all), I will go through each and every suggestion

Unfortunately, you'll have a tough time with this given your current toolchain. You definitely need a Mac (or a Hackintosh, which is still not cheap), and you really ought to have an iPhone to do development. (There is a simulator, and you can run your apps on it, but it isn't nearly as capable as a phone and doesn't give you the ability to test for things like slow network/no network connection for performance. The multi-touch is also not as capable as the real thing; if I remember correctly the phone can handle 5 touch-points while the sim can handle 2.)

This is one downside to development on the iPhone; the startup cost is somewhat prohibitive compared to Android. However, you have a massive market with the iPhone and it's about the greatest user experience in the smartphone market right now. You can read more about it from Apple, searching Google, and there are loads of books like this.

Anybody know any good tut's for iPhone development? I have written a game in AS3 and have excellent knowledge of PHP/OOP etc but I cannot get my head around the iPhone SDK or the objective C syntax and structure.

I'm in similar situation and these are the steps I'm following and the books I bought:

  1. Learn Objective C: "Programming in Objective C" by Stephen Kochan
  2. Learn Cocoa & AppKit: "Cocoa Programming for MacOS X"
  3. Learn Cocoa Touch (specific framework for iPHone): "iPhone for Programmers"

Good luck and have fun.

I'm a PHP developer, and I use the MVC pattern, and object oriented code. I really want to write applications for the iPhone, but to do that I need to know Cocoa, but to do that I need to know Objective-C 2.0, but to do that I need to know C, and to do that I need to know about compiled languages (versus interpreted).

Where should I begin? Do I really need to begin with plan old "C", as Joel would recommend?

Caveat: I like to produce working widgets, not elegant theories.

Get Cocoa Programming For Mac OS X by Aaron Hillegass. This should get you on your way to Cocoa programming. You can look up C-related programming as things come up.

K&R C Programming Language is the definitive reference that is still applicable today to C programming.

Get the Cocoa book, work though it and if you encounter any snags, just ask your C questions here :)

Yes, you're really best off learning C and then Objective-C. There are some resources that will get you over the C and Objective-C language learning curve:

And there are some resources that will get you over the framework learning curve:

Despite what Jeff might say, learning C is important for professional software developers for just this reason. It's sort of a baseline low-level lingua franca that other innovation happens atop. The reason Jeff has been able to get away with not learning C is not because you don't need to know C, but because he learned Pascal which is in many ways isomorphic to C. (It has all the same concepts, including pointers and manual memory management.)

No need to start with plain C. Start with an excellent book instead: Cocoa Programming for Mac OS X.

Possible Duplicate:
What are best practices that you use when writing Objective-C and Cocoa?

Does anybody know a good reference about Objective-C/Cocoa Best Practices?
Project organization, methodologies, naming and etc.

A great "K&R" style reference for objective-c is Programming in Objective C by Stephen G. Kochan.

I am not sure if StackOverflow is the right service to ask this question but I believe it worths to try.

I am an experienced PHP developer and now interested in building some iPhone apps. I have searched on Google for tutorials about objective-c but couldn't find a good one for beginners.

Do you have any suggestion, something like Objective-c for dummies? :)

Thanks again.

Programming in Objective C is a great book to start off with. It's written in a similar fashion as Kernigan and Ritchie's C book. It starts at the very beginning and doesn't make too many assumptions about prior knowledge.

I learnt using this book:

http://www.amazon.com/Cocoa-Programming-Mac-OS-3rd/dp/0321503619

It's really fantastic and covers everything you'll need for making Cocoa Apps. A lot of the stuff you'll learn there is directly transferable to writing iPhone apps.

Another thing you can do is find a few open source iPhone apps to learn from, a good place to start would be http://www.appsamuck.com/, they have a bunch of examples apps you can take a look at.

If you're just looking for an obj-c language guide Apple has a pretty good one:

http://developer.apple.com/documentation/Cocoa/Conceptual/ObjectiveC/Introduction/introObjectiveC.html

My question is How to move a ball in cocos 2d using Space manager.but when the ball move the screen will also move like angry bird.

Thanks In Advance.

"Learning Cocos2D" by Strougo and Wenderlich is pretty good, although there are some omissions. For example it doesn't discuss how to save state, although people might be expected to look elsewhere for that because it's standard iOS. http://www.amazon.co.uk/Learning-Cocos2D-Hands-Building-Addison-Wesley/dp/0321735625

On the other hand, Ray Wenderlich's website is fantastic and discusses a lot of stuff that doesn't make it into his book, including saving state. http://www.raywenderlich.com/

Also check out the official Cocos2D programming guide, which is probably how many of us got going. http://www.cocos2d-iphone.org/wiki/doku.php/prog_guide:index

If you don't actually know Objective-C yet, or any other language, Kochan's book is good: http://www.amazon.co.uk/Programming-Objective-Stephen-G-Kochan/dp/0672325861

If you already know something like Java, C++, or C# then O'Reilly's Objective-C Pocket Reference is like a mini-conversion course. It's pretty old but everything in there is stuff you'll still need. http://www.amazon.co.uk/Objective-C-Pocket-Reference-Andrew-Duncan/dp/0596004230

I am currently moving from C to Objective-C and, to me, this code seems to be all find a dandy but Xcode thinks otherwise. I got this code sample from the internet and have been relentlessly trying to correct it and I've come to a deadend:

#include <objc/Object.h>

@interface Greeter:Object
{
    /* This is left empty on purpose:
     ** Normally instance variables would be declared here,
     ** but these are not used in our example.
     */
}

- (void)greet;

@end

#include <stdio.h>

@implementation Greeter

- (void)greet
{
    printf("Hello, World!\n");
}

@end

#include <stdlib.h>

int main(void)
{

    id myGreeter;
    myGreeter = [Greeter new];

    [myGreeter greet];

    [myGreeter release];
    return 0;
}

The error seems to be on the myGreeter = [Greeter new]; line and the Xcode isolates the problem as something about Thread 1. Do I need to alloc/init anything?

Below is the console log:

[Switching to process 1833 thread 0x0]
2011-04-18 21:52:10.323 PROJ[1833:903] *** NSInvocation: warning: object 0x100001160 of class 'Greeter' does not implement methodSignatureForSelector: -- trouble ahead
2011-04-18 21:52:10.326 PROJ[1833:903] *** NSInvocation: warning: object 0x100001160 of class 'Greeter' does not implement doesNotRecognizeSelector: -- abort
sharedlibrary apply-load-rules all
Current language:  auto; currently objective-c
(gdb) 

Your example uses the GNU runtime and thus is a bit deprecated. The compiler defaults to the NeXT runtime but can be set to use the GNU runtime with the compile option -fgnu-runtime

You should look into grabbing a good book about Objective-C like "Programming in Objective-C" by Stephen Kochan

http://www.amazon.com/Programming-Objective-C-Stephen-Kochan/dp/0672325861

I have both Stephen Kochan's Programming in Objective C published in 2003 and Programming in Objective-C 2.0 (2nd Edition) published in 2009. Both are excellent books, and I am refreshing my Obj C skills.

In both editions, there is a listing for the Fraction with Classes program. It is listing 3.4 in the first edition, listing 3.2 in the second edition.

Here is listing 3.4 from the first edition:

#import <stdio.h>
#import <objc/Object.h>
///Interface section
@interface Fraction: Object
{
    int numerator;
    int denominator;
}

-(void) print;
-(void) setNumerator: (int) n;
-(void) setDenominator: (int) d;
-(id)init;

@end

//Implementation section

@implementation Fraction;
-(void) print
{
    printf(" %i/%i", numerator, denominator);
}

-(void) setNumerator:(int)n
{
    numerator=n;
}

-(void) setDenominator:(int)d
{
    denominator=d;
}

-(int) numerator {
    return numerator;
}

-(int) denominator {
    return denominator;
}

@end   //Implementation

// Program section
int main (int argc, const char * argv[])
{
    Fraction *myFraction;

    myFraction=[Fraction alloc];
    myFraction=[Fraction init];

    [myFraction setNumerator:1];
    [myFraction setDenominator:3];

    printf("The value is:");
    [myFraction print];
    printf("\n");

    [myFraction free];

    return 0;
}

The second edition became much more Apple/OS X centric. Instead of focusing on GCC, the text is more focused on xcode. Instead of the generic objc/Object.h import, the listing were translated to use the OS X Foundation class framework.

Here is listing 3.4 from the second edition:

// program to work with fractions - class version  

#import <Foundation/Foundation.h>  

//---- @interface section ----  

@interface Fraction: NSObject  
{  
    int numerator;  
    int denominator;  
}  

-(void) print;  
-(void) setNumerator: (int) n;  
-(void) setDenominator: (int) d;  

@end  

//----@implementation section ----  

@implementation Fraction  
-(void) print  
{  
    NSLog (@"%i/%i", numerator, denominator);  
}  

-(void) setNumerator: (int) n  
{  
    numerator = n;  
}  

-(void) setDenominator: (int) d  
{  
    denominator = d;  
}  

@end  

//---- program section ----  

int main (int argc, char *argv[])  
{  
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];  

    Fraction *myFraction;  

    // Create an instance of a fraction  

    myFraction = [Fraction alloc];  
    myFraction = [myFraction init];  

    // Set fraction to 1/3  

    [myFraction setNumerator: 1];  
    [myFraction setDenominator: 3];  

    // Display the fraction using print method  

    NSLog (@"The value of myFraction is:");  
    [myFraction print];  
    [myFraction release];  

    [pool drain];  
    return 0;  
}   

Of course the older version does not compile on the newer XCODE, and I do not find that terribly surprising. However, the older edition code no longer runs if compiled on recent versions of GCC on Linux or Windows.

The specific run-time error is init method not found but the Kochan book states that the init method need not be defined on a class derived from Object. Indeed you do not need to define -init -alloc or free on NSObject but gcc 4.2.1 warns that they are not defined for Object. I am assuming that this code could be successfully compiled and executed when Kochan put out his first book. The Foundation classes and NSObject, I believe, are Apple only.

I can compile and run 30 year-old C code, but 7 year old Objective C is not longer useable? Has Objective C, essentially, become an Apple only language with no real support outside of Apple only compilers and technologies? That is the question.

I just recently made the move to Objective-C. I am doing some exercises from Kochan's Programming in Objective-C 2.0. On this particular exercise, I am asked to modify the print method with and optional argument:

-(void)print{
  NSLog(@" %i/%i ", numerator, denominator);
}

For this I simply created another print method that would take a BOOL argument and modified the existing print method as follows:

-(void)print{
  [self printReduced:FALSE];
}
-(void)printReduced:(BOOL)r{
  if(r){
    [self reduce];
  }
  NSLog(@" %i/%i ", numerator, denominator);
}

But for the last part of the exercise, I am supposed to use that BOOL to determine if the Fraction should be reduced or not (no problem testing the flag), but when reduced I am not supposed to modify the original object. For this I allocated a new Fraction object inside the printReduced method and released it before the end of the method too:

-(void)printReduced:(BOOL)r{
  Fraction *printingFraction = [[Fraction alloc] init];
  [printingFraction setTo:numerator over:denominator];
  if(r){
    [printingFraction reduce];
  }
  NSLog(@" %i/%i ",[printingFraction numerator], [printingFraction denominator]);
  [printingFraction release];
}

My question is: Is it right to create and release objects whithin a given method this way? This seems to do the work just fine without modifying the original Fraction, but is this the right approach?

This is correct. Whenever you 'alloc' an object, you own it. Before it goes out of scope (the end of the method in this case), you must relinquish ownership, a release in this case.