Learn Objective-C: Day 2

Learn Objective-C: Day 2

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

Welcome to part two of this introductory series on Objective-C. After spending last week reviewing the fundamentals of the C language upon which Objective-C is built, this week we will transition to focusing on what makes Objective-C such a great language for software development. Specifically, we will discuss the fundamentals of Object Oriented Programming (OOP) and demonstrate how to create a class and send messages to objects in Objective-C.

Object Orientated Programming

Why do we have Objective-C? Why not just use the underlying C language? The reason we have Objective-C is to give us an object oriented playground within which to build our applications. OOP is a programming paradigm that attempts to allow developers to think about software design in terms of objects and attributes instead of variables and functions. Specifically, OOP attempts to obtain data abstraction, encapsulation, modularity, polymorphism, and inheritance. The topic of OOP could easily fill a book (or a tutorial series) on its own, so instead I’ll introduce you to the basic principles by way of example.

Imagine that you have a car. You can think of your car as an object. There are many other cars in the world and you might even own more than one. Your car has various properties to it: make, model, color, engine type, and many more. In Object Oriented Programming terms, we would call the abstract concept of a car a “class” and the individual car that you own an object or instance (instantiated object) of the class. When a new car is manufactured, a new instance of the car class is instantiated (or created) and given its own set of properties.

Still a little fuzzy? Another great analogy is that of the cookie and the cookie cutter. The class is the cookie cutter, and the object is the cookie.

So, why think in terms of objects? One of the best reasons is because this is how your brain naturally conceptualizes life in the real world, and there are many benefits to being able to abstract software development in similar terms.

Classes (and hence objects) are made up of methods and attributes. If you come from another programming language, you may be more familiar equating methods with functions and attributes with variables. We will discuss each in turn next.

Methods

So we have an “instance” of a car, now that what do we do with it? Well, we drive it and fill it with petrol, among other things. Driving and filling with petrol apply only to the cars that we use, meaning that when we fill up a car or drive a car, we are only impacting one instance, and not all the cars in the world. Therefore, filling up the car instance is considered an instance method. Itʼs something we do to our instance and only our instance.

On the other hand, if we ask the original car class how many colors of car are available, this is a class method because we are no longer only talking about the car we drive around but all cars in general.

Many of these principles become more clear with use, so letʼs look at a little bit of syntax.

In Objective-C, we call object methods by passing messages. When we want to know how much gas is in our instance of car, then we send a message to our instance and the message is the method we want to apply. Programmatically it looks like this:

[recipient message];

The brackets indicate we are sending a message. The first parameter is who should receive this message and the second parameter is what the message actually is. Finally, we end with a semi-colon as is common to most programming languages.

So, with our previous example in mind, this is how we would interact with our instance of car to add gas to the tank;

[dansCar addGas];

The example above assumes that we have instantiated an instance of the Car class and named it “dansCar.” We then pass the “addGas” message to the object “dansCar,” which is the equivalent of calling a function. In another language, this line might look like:

dansCar.addGas();

Attributes

Letʼs say our car class has a gas tank thatʼs stored as a percentage. For example, if the gas tank is at 50% then it is half-full and if it is at 100%, it means it is full to the brim. Now, if we want to know how much gas is in the tank, we donʼt just directly take that information from an attribute. Instead, we would use an accessor method to access the internal variable for us. Likewise, when we want to fill the tank, we donʼt just give the gas tank attribute a new percentage, we use a setter to update the attribute for us. This process is known as data encapsulation.

What we mean by data encapsulation is that data is contained (so to speak) by methods meaning to access it we need to use methods. Some of you who have programmed in other languages and havenʼt heard of data encapsulation may be wondering why we do things this way. The answer is that by encapsulating data, there is a nice cushion between the developer of a class and the user of a class. Because the class methods manage and maintains the attributes within the class, they can more easily maintain data integrity. Another major benefit is that when a developer distributes his class, the people using it donʼt have to worry about the internals of the class at all. A developer may update a method to make it faster or more efficient, but this update is transparent to the user of the class as he/she still uses the same method with no change to his/her code.

This brings us nicely on to the next section weʼre going to look at, which is how Objective- C separates interface from implementation.

Interface and Implementation

When you create or work with a simple class in Objective-C you will see that it, by default, has two files. One is the implementation file which is a file that ends with a suffix of .m and the interface file which is a file that ends with a suffix of .h.

Interface

#import 

@interface Car : NSObject {

    //This is where attributes go
    float fillLevel;

}

//This is where methods go
- (void)addGas; 

@end

First of all, weʼre importing Cocoa.h which is a standard library with a lot of reusable code that we can use inside our app.

Next, weʼre declaring that this is the interface for the Car, but weʼre also putting NSObject into that declaration. Adding “: NSObject” means that the Car class inherits from the NSObject class. We’ll talk more about inheritance in a future tutorial.

Our instance variable “fillLevel” is declared next, and we specify that it is of the “float” data type so we can easily represent a percentage.

The next line declares our “addGas” method. The “-” indicates that this is an instance method, not a class method. The “(void)” portion means that the method will not return anything back when it finishes executing. If the class was going to return an integer, this would be changed to “(int)” and the same for any other data type. Finally, we finalize the method declaration with a semicolon.

Implementation

#import "Car.h" 

@implementation Car

-(void) addGas {
    // code goes here to add gas
}

@end

The implementation in this case contains the method to add gas to the tank. We also import Car.h, which is the interface file. Where our addGas method sits, we could add many more methods, but today’s scope is to simply get you to understand how classes work rather than make a fully-fledged class.

Next Time

Next time weʼll be looking more in depth at methods and at using variables with methods (as well as the basics of managing variables in Objective-C). This tutorial wasn’t too long as itʼs often a bit confusing for new developers as to why we separate classes in to more than one file. If youʼre feeling at all confused then please re-read the above or ask questions in the comments section below. Classes will be a constant reoccurrence in this series and itʼs important you understand how they work.

Challenge

Seeing as this part of the series was fairly theoretical, thereʼs not too much you can do to practice. However, I do recommend this week that you sign up for Appleʼs developer website as itʼs an invaluable reference. Once youʼve done that, have a snoop around some of their downloadable classes and download a few simple ones. You donʼt need to understand all of the code, just look at how the classes are formed and separated across files.

Series Navigation«Learn Objective-C: Day 1Learn Objective-C: Day 3»

Add Comment

Discussion 33 Comments

  1. adrian says:

    It's pretty confusing to mix curly brackets with things like @end for containing blocks of code. I don't understand why apple didn't go with C++ for an object oriented C, it looks a lot nicer :)

  2. Thank you for this! I've been learning how to code iPhone apps via an awesome book by Dave Mark, but it assumes basic Obj C knowledge, so I never understand why classes and objects were structured like this :)

  3. aaran says:

    hope to see alot more content coming to this site.. apple have brought out a new xcode today so that should help alot.

  4. Ed says:

    Thanks – this series is very useful

  5. Scott Munn says:

    Please publish more of these, and very soon. This could be a huge asset to Envato, and I am already looking for alternatives out there.

  6. Mohit says:

    this is something really great …

    i nice way to kickstart app development

    thnx !

  7. elomarns says:

    Posting the comment again to include the code:

    But, I didn't understand the import code on the interface. This is the code on the post:

    #import <cocoa cocoa.h="">

    But usually this is what I see:

    #import <Cocoa/Cocoa.h>

    Even Xcode generate code like the one I post when you use one of its templates.

    • Dan says:
      Author

      Hey elomarns, the one you usually see is right – but it’s also what I see above on the tutorial? It could be a problem with your browser or similar, I believe the scripts used to display code here could be the reason it’s showing up like that on your browser – sorry about that!

  8. Patrik says:

    Dan, I really enjoy this tutorial series on Objective-C. I can’t imagine any better way to learn the basics. It has really gotten me going. Thanks allot!

  9. BEN says:

    Loving this series, useful starting place for entry into the sdk and development.

    Keep it up, looking forward to the rest.

    Thanks

  10. rakesh says:

    hi
    this tutorial is awesome for the beginners….i am not much familear with c++ or c…..so can you tell me how can i learn objective c effectively….and if want to develop advanced application so what should i prefer…thanks

  11. Sohan says:

    Hi.

    will i be able to compile these 2 files? because i tried to do so and got an error.

    car.h:15: error: expected identifier before ‘/’ token
    car1.m:9: warning: ‘@end’ must appear in an @implementation context

    i tried compiling it using gcc on OS X. just used the command gcc car1.m

    Thanks for the very helpful tutorials though!

  12. sohan says:

    i solved this using this command – gcc car.m -ObjC -framework Foundation

  13. James says:

    Wow, thanks for the info. I’ve bookmarked this site. I come from a background in C#, so some of the concepts are familiar – But declaring instance variables and methods in one file, and implementing them in another file is a new concept.

  14. Charlotte says:

    Wonderful tutorial! Very helpful..

    On a side note, I want to point out that when you say “developer” you only use “his” but when you are talking about the “user” you use “his/her”. Not all developers are guys. Just thought you should know. :)

  15. shital says:

    hello,
    I have created two different files one for ‘@interface’ and one for ‘@implementation’ now how can I compile and run whole program?

  16. George Gray says:

    Wow, just working my way through these excellent tutorials. Head is spinning a little but great stuff !

    • Dan Walker says:
      Author

      Thanks George, when I learn something new like this I find the best thing to do is make notes as I read with pen/paper – then if anything at all isn’t clear, re-read it. Good luck!

  17. Ian Dunn says:

    Dan,

    Thanks so much for putting out such a detailed tutorial. I am a relatively new programmer with some knowledge of Python and I am trying to understand Objective C and compare it to what I have learned in Python. Here is a quote from this lesson: “Our instance variable “fillLevel” is declared next, and we specify that it is of the “float” data type so we can easily represent a percentage.” What makes “fillLevel” an instance variable rather than a class variable? The Python tutorial I read led me to believe that a class variable only exists once and all instances of the class reference that class variable, while an instance variable is unique to an instance, and hence there are many unique instance variables for each object of a class. I am trying to understand what makes “fillLevel” an instance variable. If you are familiar with Python, are instance variables defined differently in Objective C than Python? Thanks so much.

    Ian

  18. Nate Dog says:

    hi,

    I was wondering do you need to know OOP to be able to program apps using xcode. it would be nice if someone could help me out.

    thanks

  19. Francis Mitchell says:

    I think these tutorials are very good. The only improvement is to add a quick reference glossary, so you can easily learn what all the words like float and interface mean in coding.

  20. Symeon says:

    Ditto – superb tutorial, to the point and easy to read tutorials. Too many books out there that either assume previous experience, or if you’re an absolute beginner, they speak to you like you’re a 5 year old!

    Did anyone find a fix about the font problem that elomarns had above showing:

    #import

    Instead of

    #import

    I’m having the same problem in safari and firefox although it shows the second version on my iphone in safari.

    Because I’m a complete beginner I’m not sure which is correct and if there will be other errors like this along the way.

    Thanks in advance…

  21. Symeon says:

    uh! That last message didn’t even show up the code I typed after the #import after I pressed ‘add comment’!!! What is going on here??? :-(

  22. sandeep says:

    i dont understand car part..i mean actully what is the car in above example..
    whether it is actully interface or class??????if it is class then why @interface has been used?????????

  23. DK says:

    Hi Dan

    Great Stuff !! i just read the Day 1 and gained confident that i can learn obj c and just completed Day 2 and felt really confused and bad. I think i need to learn the OOPS concept first, and then should start this tutorial. I am really new to c and c ++ stuff while I have great knowledge in INFO BASIC language and felt lot to learn before i start. Thanks for the tutorial and wud be great if u can suggest me anything.

  24. Jordan Warkol says:

    Hi, this is great, hopefully comments are still going for this and being responded to since it’s almost a year from the beginning.

    Like some other people here, I am very new, and a complete beginner when it comes to any programming or language learning.

    I read a pdf on the apple developer site explaining OOP in more detail, and read the first tutorial along with this second one too.

    I am wondering what is the best way for me to learn in the proper order. This tutorial, or a basic document explaining the C language?

    If anyone can help me with this, and some links to places of where to start I would appreciate it greatly.

    thanks

    Jordan W.

  25. Mike says:

    Thanks Dan! Best tutorial I’ve seen on ObjC so far. Easy to learn thanks to your clear examples and easy to read code. You’re a champ!

Add a Comment

To add a code snippet to your comment, please wrap your code like so: <pre name="code" class="html">YOUR CODE</pre>. You can replace the class name with "js," "css," "sql," or "php." If there are any "<" or ">" within your code, please search and replace them with: &lt; and &gt; respectively.