Learn Objective-C: Day 3

Learn Objective-C: Day 3

Tutorial Details
  • Technology: Objective-C
  • Difficulty Level: Beginner
  • Completion Time: 20 - 35 Minutes
This entry is part 3 of 6 in the series Learn Objective-C

Welcome to part three of this series -I hope youʼre enjoying it! Last week we looked at how we separate classes in to separate files (interface and implementation), this week weʼre going to look at classes again, but a little bit more in depth. Weʼll also take a peak at inheritance and how it works, along with variable scope.

So far, we have had some great feedback via email, twitter and comments. Itʼs great to see so many people are interested in this subject and itʼs even better to see that so many of you are trying it out for yourself and asking some great questions. Keep it up!

In Review: Classes & Objects

Letʼs review what we have learned about classes in this series so far. If you donʼt know any of this, feel free to skim back to the last tutorial to re-cap. Ok, so, what are classes?

A class is a collection of encapsulated data and custom methods. A class may hold many different kinds of data, and the class methods usually (but not always) perform action related to that data. In Objective-C, a class is usually composed of two files: an interface file and an implementation file. The interface file uses the .h file extension by convention and is where the person using the class can quickly find the methods and data members available to the class. The implementation file uses the .m file extension by convention and is where the majority of the code resides because it contains the actual implementation of all the functions declared in the interface.

So, what makes a class different from an object? What is an object? An object is an instance of a class. Think back to our example with the car in the last part of the series. Where car is the class, then myCar, dansCar, and yourCar would all be objects because they are instances of the car class.

Classes from Apple (and some history)

Before we carry on, Iʼd like to share a few (of many) common classes youʼll be using a lot that are provided by Apple, but first a quick history lesson.

Many classes Apple provides are prepended by the abbreviation “NS”, which stands for NextStep. When Steve Jobs left Apple, he founded NeXT, creating workstation computers that ran on its operating system. The object orientated programming language used on those machines was called NeXTSTEP, which is where we get the “NS” from. When Apple ʻacquiredʼ (another history lesson in itself) NeXTSTEP, they decided to base Mac OS X on NeXTSTEP.

Here are some simple, common classes weʼll see a lot of:

  • NSString is a string of text that is immutable.
  • NSMutableString is a string of text that is mutable.
  • NSArray is an array of objects that is immutable.
  • NSMutableArray is an array of objects that is mutable.
  • NSNumber holds a numeric value.

Weʼll learn many more later on, but for now the above will come in handy. Youʼre probably wondering what mutable and immutable means, which is an entirely reasonable question. If an object is immutable that means when we create the object and assign a value then it is static. The value can not be changed. If an object is mutable then it is dynamic, meaning the value can be changed after creation.

Pointers and Initializing

Letʼs say we want to make a static string of text and log it, how would we go about it? In our code it would look something like this:

#import <Foundation/Foundation.h>
int main (int argc, const char * argv[]) {
    NSString *testString;
    testString = [[NSString alloc] init];
    testString = @"Here's a test string in testString!";
    NSLog(@"testString: %@", testString);
    return 0;
}

I created this file in XCode by going to File > New Project > Mac OS X > Application > Command Line Tool > Type: Foundation (quite a journey!) and editing the implementation (extension: .m) file in the project.

There are quite a few things here that are new, so letʼs examine the above piece by piece.

First of all, we import the foundation library (this is because we set type to Foundation in the new project window before).

int main (int argc, const char * argv[]) {

This declares the initial function that will be called when our program begins execution. The two parameters separated by a comma are for passing arguments to our application. For now, donʼt worry about these as we wonʼt be needing them right now.

NSString *testString; testString = [[NSString alloc] init];

We now create a pointer to an NSString object called testString. Once the first line of this is finished, no string exists yet, only a pointer to a string that we have not yet created. On the next line, we create the string our pointer points to.

We could have alternatively written the last line like this;

testString = [NSString alloc];
[testString init];

This may seem a little confusing at first. In the first version, we have nested the statements within brackets on the same line, whereas in the second we have separated the statements into two lines. The method init initializes all the instance variables in the class.

testString = @"Here's a test string in testString!";

This line is pretty self explanatory, the reason we prepend the quotes with an @ sign is to tell the compiler that the following text is an NSString.

NSLog(@”testString: %@”, testString);

Here we log some information to console. XCode has a debugger built in that you can find under the Run menu. It is very useful when developing an application to log when events are happening and the values of certain variables – it can help when troubleshooting your application and debugging problems. This method works like printf (remember from the first week?) where we supply a string of text with a replacement character (%@ means an Objective-C object).

Learn Objective-C

Finally we return 0, which we know just tells the operating system that the application ended with no problems.

Inheritance

Remember when we made our NSString earlier, we used the init method? Well NSMutableString, NSArray and in fact, every single NS class, also uses init. Seems a lot of wasted code to put the init method in each class, right? It would be, thatʼs why init is usually only implemented once, in the root class known as NSObject. Because classes inherit from each other, a class that is created as a child of another, parent class will automatically gain access to the parent class methods.

Letʼs take NSMutableString for example. NSMutableString has NSString for a parent (making it a child), meaning it inherits from NSString. Meanwhile. NSString has NSObject as a parent, so it inherits from NSObject.

Learn Objective-C

So for example, NSObject has a method called init, so each subclass has this method implemented – which is called a class method. As a matter of fact, the init method in NSObject doesn’t actually do anything it simply returns self. The reason for this is that methods can be overwritten. So the NSArray class may override the init that it inherits to add functionality to it – such as making sure memory is available or preparing any instance variables it may need.

As demonstrated, this is useful because it means that in addition to inheriting from classes we can also extend classes. When we extend a class, we take an existing class and add additional functionality to what is already available. This means you could create your own version of NSString with additional methods, such as a method to fill the string with random text or perform some sort of character encoding.

Summary

At this point, the fundamentals of how classes work should be clear. To test your comprehension, see if you can answer the following questions in your mind:

  • What is the difference between a class and an object?
  • Why do we use classes?
  • Why is inheritance useful?

Since classes are such an important part of Objective-C, itʼs important to really feel comfortable working with them. Last week we started looking at classes and this week we have gone into more depth. Next week, you may be glad to hear, weʼre going to move away from the theoretical side and start working on our own simple class or two to perform simple tasks.

Homework

Since we have mainly done theory so far, your homework this week is to surf Appleʼs developer website (you should have done this last week) and look at some of the classes available. If you donʼt know where to start, start with something such as NSString. Youʼll become more comfortable with the details of the parent class, the methods, and so on. This will be important later on when youʼre using classes outside of this series and you want to know what methods they inherit or use.

Next Time

Weʼll get more practical next week with some class coding. Classes really are central to Objective-C, so itʼs mega important that you come to grips with them and the goal of this series is to really ensure that you do!

As usual, if you have any questions or comments, you can reach me by dropping a comment or email. If youʼd like to get in touch with me personally and get a quick answer, send me a tweet!

Series Navigation«Learn Objective-C: Day 2Learn Objective-C: Day 4»

Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • http://www.amberweinberg.com Amber Weinberg

    Thanks for all the theory stuff about Objective C. I’ve done several simple apps from an awesome book, but they don’t go very deep into the actual workings of Objective C and it’s syntax.

    • http://www.dans-blog.com Dan
      Author

      Hey Amber =] It’s just as important to learn the theory and inner workings of a language than just the syntax. We’ll soon be looking at syntax too, but it’s easier to learn when you know what’s going on under the hood!

  • http://Imperativedesign.net Paul

    What’s the difference between NSInterger and NSUInteger?
    Liked the tut btw!! :)

    • http://www.dans-blog.com Dan
      Author

      Hey Paul, the U signifies that the latter is an Unsigned integer, it’s only really handy when you’re dealing with much bigger numbers than NSInteger can handle. If it interests you, do a quick search for unsigned and signed integers with 32+64 bit systems =]

  • http://www.codecanyon.net/?ref=TutelageSystems Mickey

    It would be nice to see an Objective-C tutorial go from scratch to working application such as a note taker, or just something simple :)

    • http://www.dans-blog.com Dan
      Author

      Hey Mickey, once we’ve learnt all the theory we’ll get in to more programmatic examples =]

  • http://www.rubelux.net Ruben

    Thank u very much, can’t wait for next tutorial, I love them, it’s the best introduction object c tutorial that you can find on web, great stuff, please keep doing it.

    Rubelux

  • Smit

    Seriously, thank you! This is exactly the type of basic material I have been looking for!

  • http://www.engram.nu Niklas

    Indeed thanks for this series! Like your way of explaining and the post setup!

    • http://www.dans-blog.com Dan
      Author

      Thanks, I try to keep it simple and friendly – like how you’d learn in a classroom!

  • Ibrahim

    Thanks Dan for the wonderful series

    but I didn’t understand why we should write this code:

    testString = [[NSString alloc] init];

    because I comment it and I didn’t get any error.

  • littlevsp

    what does it mean to “allocate”(alloc) and “deallocate”(dealloc) something?

  • maya

    “Letʼs say we want to make a static string of text and log it…”

    what do you mean by “log it” exactly?

    thank you….

    • http://www.mondaynightcrew.com/ Daniel

      “Log it” means that the static text string will post to the Xcode console once the program is built and run. You can find that under Xcode -> Run -> Console. It’s useful for quickly getting data on a program after a build.

  • http://mobile.tutsplus.com/tutorials/iphone/learn-objective-c-day-3/ vikram

    This site is very helpfull to novice of Objective-C.It performs superb information to the users.

  • Deb

    really thankful to you for the awesome tutorials

  • MRB

    Hi Dan, I’m just struggling with something if you can perhaps shed any light.

    [quote]
    testString = @”Here’s a test string in testString!”;

    This line is pretty self explanatory, the reason we prepend the quotes with an @ sign is to tell the compiler that the following text is an NSString.
    [/quote]

    Why is it necessary to tell the compiler to expect an NSString? The object “testString” is already of type NSString, surely that’s the idea of assigning object types. I just can’t get my head around why the compiler would not already be expecting to assign a value of the correct type.

    Thanks for the tutorial and for any explanation you can offer to my question.
    Mark

    • http://none.com Bil

      Simple answer is that yes, it should be possible for compiler to know what type of object is needed (NSString) and make it work…. but compiler doesn’t work that way.

      There’s a long history with C coming into play here that we don’t need to care about, except to note that the compiler works the way it does because Objective C is a superset of plain C.

      So… We as humans look at it and know that an NSString is clearly needed.

      But compiler looks at it, and if it does not see the @ instruction to create an NSString it has no idea whether:
      a) you made a mistake, and just goofed the code by leaving out the @
      b) you made a mistake, because you think a plain C string should work, and your logic is wrong

      If the compiler just “corrected” it for you, your program might not work the way you expect (and you wouldn’t understand why), and so it leaves it alone for you to fix yourself because you know what the right “fix” is better than the compiler does.

      (obviously pretty simple case here; but there are other much more complicated cases where the compiler can’t make any intelligent assumptions about how to “fix” a value that doesn’t fit a variable type… so it leaves them all for you to handle rather than guessing at what the right fix might be.)

      • guy with computer

        then when is something in quotes is not a string? by this reasoning, the compiler should then wonder if you meant to type any characters, and not just wrote 200+ lines-worth of typos.

        why exactly is this redundancy essential? it would help me understand the language – what is to be understood (even dimly) and what are just random features with no meaning. is there a function here in terms of the allocation of memory. or is this syntax the byproduct of some slight human oversight in the design of the objc language?

        likewise, a similar redundancy seems to occur in (mentioned in comments above) …

        testString = [[NSString alloc] init];

        (as opposed to say, char* testString; )

        Are these simply human conventional redundancies (weak spots in the design of the language) or formal logical ones (complicated but understandable)? At least for me, there is too much to memorize as it is at this early stage, without memorizing exceptions to the logic.

  • Anshuman

    Hi Dan,

    I have read this tutorial it’s too good, I learn lots of things from there.
    I am feeling some problem on table view, plz provide any tutorial based
    on table view.

  • Marcus

    Hi Dan,

    I am really impressed with your tutorials, it has offered so much more explanation about objective-c than other tutorials have, thank you very much.

  • wasemm shah

    This is good for every one . I learn more but here some concepts are mix .This become more good if every concept tell and describe sepretly .

  • Kelvin

    Thanks so much for this tutorial. I’ve seen many tutorials on Objective-C and by far this is the best one!

  • Umesh

    hi, i dont have any MAC machine. i run this app using mingw32. i face some problem while running the xcode program to it.

    #import

    int main (int argc, const char * argv[]) {

    NSString *testString;
    testString = [[NSString alloc] init];
    testString = @”Here’s a test string in testString!”;
    NSLog(@”testString: %@”, testString);

    return 0;

    }

    is there any chance to runthis program through my windows OS.

    • prakasha maravanthe

      I think you just had to add to the #import then it would be #import
      that’s all

  • Umesh

    hi, i dont have any MAC machine. i run this app using mingw32. i face some problem while running the xcode program to it.

    is there any chance to runthis program through my windows OS.

  • Eduardo

    Hi, as well as Umesh I do not have a Mac, I use Linux (Ubuntu 11.04) and I am compiling in the terminal with gcc.
    I have a problem while compiling, the compiler returns me:

    bash: error sintáctico cerca del elemento inesperado `1′

    In English it would be:

    bash: syntactic error near the unexpected element `1′

    Why is this?
    My code is:

    #import &ltFoundation/Foundation.h&gt

    int main(){

    NSString *newString;
    newString = [NSString alloc];
    [newString init];
    newString = @”Some text”;
    NSLog(@”newString = %@”, newString);
    return 0;
    }

    Thanks in advance!

  • vasisthabi

    Hello,

    First time into Objective c. I basically use Linux can you please feed in some links ,suggestions
    and comments to start out. Like the IDES and stuff like that.

  • nofu

    Whoa where did this alloc thing come from, why isn’t it explained ? Also, this tutorial started nice and slow, this seems like a big jump.
    I’m yet to see a tutorial which can really stand on its own, it’s always back and forth to fill in the blank spots.

  • Tom Lemon

    Sorry, another bad Obj-C tutorial.

    It jumps right in and starts talking about setters and getters without even introducing them.

    Bzzzt. Fail.

  • http://www.clivewalden.com Clive Walden

    Thanks! Great introductory tutorial for an experienced Pascal, Java and Delphi programmer.
    One thing I don’t understand is the Obj-C use of alloc.
    In the world I come from, you could not allocate memory for an immutable string before you knew
    what it was (i.e. its size/length).

  • Shai

    first of all, thnx for the tutorials!
    one thing i didn’t understand:
    if the object we created is NSString, and not NSMutableString, then how can you assign a value
    to it after the initialization?and how can i change its value?

    for example, this code runs without any errors:

    #import

    int main(int argc, const char * argv[])
    {

    NSString *testString;
    testString = [[NSString alloc] init];
    testString = @”ABC”;
    testString = @”B”;
    NSLog(@”testString :%@”, testString);
    return 0;
    }

    ty for your time
    Shai.

    • Linish

      Hello Shai,

      The basic difference is we can append more data to an existing string if it is mutable.
      Following example might help you

      NSString *testString;
      testString = [[NSString alloc] initWithString: @”Here’s a test string in testString”];
      NSLog(@”testString: %@”, testString);

      NSMutableString *testMutableString;
      testMutableString = [[NSMutableString alloc] initWithString:@”Here’s is a test string in testMutableString.”];
      [testMutableString appendString:@" Newly Appended String"];
      NSLog(@”testMutalbleString: %@”, testMutableString);

  • Stephen Johnson

    There are many comments above regarding this, here’s an answer to simplify:

    NSString * testString; -> This creates a “pointer”, something that will always “point to an NSString”.

    This line:
    testString = [[NSString alloc] init]; is -unused-… what this does is “make space for a string, then tell testString to point to that string”. However, the string it creates is just a blob in memory that looks like: @”". Aka, empty.

    The next line creates a string and assigns it to testString. So this: @”This is a string” is really a shortcut for:
    [[[NSString alloc] initWithString:@”This is a string”] autorelease];

    You don’t have to worry about “autorelease” on a Mac, but you do on an iPhone. Anyway, to finish my explanation…

    testString is now “pointing to” the next string he creates, but the memory for the string created with [[NSString alloc] init] is still sitting somewhere, and it can’t be freed anymore because we are now “pointing to” something else.

    Think of Pointers (eg: testString) like suitcase handles, and the objects they point to (NSString in this case) like the suitcase. Once you lose the handles to the suitcase, it’s all over with.

    This tutorial is based on Macintosh programming, so the operating system will handle the “leaked” string, no worry. I’m here to review, but I find the tutorial nice and simple to follow.

    I highly recommend Arthur Griffith’s advanced C/C++ videos if anyone wants a clear explanation of pointers, bits, and char’s (new books just don’t teach that, it’s quite annoying when trying to help other programmers)

  • Omul

    Please recheck the meaning of static and const. You expressed that a variable which can’t be changed is static ( http://en.wikipedia.org/wiki/Static_variable ) instead of describing it as being const (http://en.wikipedia.org/wiki/Constant_%28programming%29).
    I know it’s no big deal but for someone using this as his first tutorial it will create some confusion later on.

  • picky

    Weʼll also take a peak at … you meant a peek?

  • Karthus

    Wait somone tell me if im right when i say that the pointer has the name of the object it points to. So in this case *testring(pointer) points to an NSString object testring??

  • Karthus

    no actually i got it the pointer testring points to the string -”Here’s a test string in a teststring! “

  • Roy

    Hello,

    Thanks for your great tutorial, just trying things out for myself and encountered a problem. Hope you could give me some help.

    Why wont this work?

    NSMutableString *testMutableString;
    testMutableString = [[NSMutableString alloc] init];
    testMutableString = @”Hello everyone”;

    but when I use [[NSMutableString alloc] initWithString: @”Hello”], it works?

  • Artur

    I left confused after reading this tutorial, as I haven’t found anything Dan described in previous tutorial. Neither interface nor implementation files or code. No description of alloc or the need of init. In the previous lesson you declared class attributes inside object’s { }, but now testString as an attribute of NSString goes inside function, not an object. Until now everything about classes was clear though.

  • Snarkville

    Think of yourself as the developer who wants to create a pointer(a text sign) pointing the way to Hell. It doesn’t exist so you have to create it, initialize it, declare what it should say (“This way to hell”) and you want to log the event, because hell.

  • Miguel Sánchez Villafán

    You have an error on the first paragraph of the Inheritance section, you say “parent class will automatically gain access to the parent class methods”, which I think should be “child class will automatically gain access to the parent class methods”. Thank you!