Advertisement

iOS

iPhone SDK: Objective-C Creating Custom Class

Class | Foundation | IOS | IPhone | Objective-C | Xcode

iPhone Application Development

Advertisement

This entry is part 4 of 9 in the series iPhone Application Development

Custom Class in Objective-C

Though Foundation framework contains lots of classes that we can use, we may want to declare our own custom classes. Well Objective-C allows us to do that too. Objective-C supports all that OOP concepts we need to create iPhone Application. Let’s create our first class.

Step 1. To create custom class, right click on you project directory on project navigator bar (left side bar in Xcode). Click on ‘New file’ option. You can also do that by click on menu option: File=>New=>New File. This will bring a popup box like below:

Custom class in objective-c

Select MAC OS X => Cocoa => Objective-C class and click on Next. Which shows next screen.

Step 2. Clicking on next will bring us a new screen like below:

Custom class in objective-c

 

This allows us to select the super class of the new class that we are going to create. Select NSObject for now and click next.

Note: NSObject is the base class for almost all classes in foundation framework.

Step 3. Clicking on next will bring a new screen again, which allows us to specify path of the new file just leave it at default and make sure that Project Name is checked in targets option. Name it Contact (our new class name. you can set whatever you want to).

Custom class in objective-c

 

Click on Next and you are done. This will add 2 files (Contact.h & Contact.m) in your project directory. In objective-C every class are created with 2 files Interface file (.h file) and Implementation file (.m file). Interface file contains only declaration to public methods and properties. Implementation file contains private declarations for private properties and methods and implementations for public and private methods and properties. Let’s see what we get when we created Contact.h and Contact.m files.

Step 4. Select Contact.h file and you will get code similar to this:

Custom class in objective-c

 

@interface Contact : NSObject

@end

Above code declares class named Contact and inherits from NSObject base class. This is the header file contains only declarations for public methods and properties not implementations.

Step 5. Now select Contact.m file and you will see code similar to this.

Custom class in objective-c

as we can see the code contains implementation for Contact Class.

Above code includes Contact.h header file and @implementation line creates block for implementation of Contact class. By Default, it contains init method, which is the constructor for Contact class. And it also contains some basic code that declares self object from super class’s init method and return same at end of the method.

Step 6. You can see three buttons at top right corner in editor block click on the second button and you will see the screen similar to this:

Custom class in objective-c

Editor screen is divided into 2 parts. One contains .h file view and another contains .m file view. That means we can see both class file side by side in this layout, Very useful.

Let’s move on and create some public properties.

Step 7. In Contact.h file write following code in @interface block.

Creates property for age, which is integer, property for firstname, which is NSString and another for lastname which is also NSString. Both lines contain nonatomic which means both are not thread-safe so no locking code will be generated. And the firstname & lastname properties are NSString class type so need pointer for that (* indicates it’s a pointer). So we specified strong too, which means it is strongly pointing to that memory. Memory will not be released if some pointer is strongly pointing to it. If all pointers are pointing to that memory are of type weak then that memory will be released by auto release pool. We declare 3 properties so we also need setters and getters for those properties too. Let’s create setter and getters.

Step 8. In Contact.m file write following highlighted code for setter and getter for age property.

 

Don’t worry about that complicated code.

Let’s first understand the way Objective-C declares methods.

6 types of instance methods are possible

  1. Method without argument without return type
    • Declaration: – (void) methodName;
    • Method call: [objectName methodName];
  2. Method With Single Argument without return type
    • Declaration: – (void) methodName: (type)arg;
    • Method call: [objectName methodName:argvalue];
  3. Method with Multiple Arguments without return type
    • Declaration: – (void) methodName: (type)arg1 andArg2: (type)arg2 andArg3: (type)arg3;   (and so on…)
    • Method call: [objectName methodName:arg1Value andArg2:argValue2 andArg3:arg3Value];
  4. Method without argument with return type
    • Declaration: – (type) methodName;
    • Method call: result_var = [objectName methodName];
  5. Method with Single Argument with return type
    • Declaration: – (type) methodName: (type)arg;
    • Method call: result_var = [objectName methodName:argvalue];
  6. Method with Multiple Argument with return type
    • Declaration: – (type) methodName: (type)arg1 andArg2: (type)arg2 andArg3: (type)arg3;   (and so on…)
    • Method call: result_var = [objectName methodName:arg1Value andArg2:argValue2 andArg3:arg3Value];

Objective-C uses new style of creating methods. Lots of programmers agree that it’s more convenient than normal c style declaration cause in this way we can get idea of what this argument is for. Otherwise we have to memorize which argument is for what purpose.

Now look at the code where we declare 2 methods, one for setter and another for getter for age property. Setter (setAge) accepts one argument and no return value, while getter (Age) accepts no argument and returns int value. Objective-C uses this naming convention to declare getter and setter. Getter name will be then name of the property and setter name will be set<Name Of Property with first letter Capitalize> for example setAge.

Step 9. This is not the only way to do property implementations. New version of iOS SDK, which is iOS SDK 5, uses more short method for declaring setters and getters. Remove setter & getter code and add highlighted code in implementation file (Contact.m).

Surprised! Yes this single line of code will declare those setter and getter for use and if still want to declare setter or getter our self; we can still by using that _age variable. But we will do that later.

This will still shows us that warning cause we haven’t implement the setter and getter for firstname & lastname properties. Remember we declare properties called firstname & lastname in interface that means we promised Contact class that we would implement that. So let’s implement by @synthesize feature quickly.

Step 10. Let’s use that class in our project’s main method. Open main.m file and write below code.

 

First we added #import “Contact.h”, which imports Contact class to use in main.m file. Then in main method we declare a pointer of type Contact and allocate memory. Got confused with this sentence.

Contact *c = [[Contact alloc] init];

Objective-C allows us to write nested method calls like Contact class has a class method (Remember its class method so we use class name instead of object name) alloc which creates memory and another is init which initialize the object and returns object of that whose reference is then stored in *c. again confused! Init is the constructor and we get that by default but we haven’t created alloc method then where it comes from. It comes from parent class (NSObject).

Next we use age, firstname & lastname properties to store value in it and then output them using NSLog. Calling class and instance methods are also called message passing in Objective-C. If we hit Run, output will be like this:

Custom class in objective-c

Step 11. We created 2 properties. Now its time to add some methods to our class. Open header file for contact class (contact.h) and add highlighted code.

we declared instance method fullname by indicating ‘–‘ at start od the method signature.

- for instance method

+ for class method

By wring this line in interface we promise that we will implement this method in our implementation. So let’s do that first. Open implementation file (contact.m) and add highlighted code in it.

We used NSString class’s stringWithFormat method to join 2 NSString Object and output concatenated string. Now lets use this in main.m file. Update the highlighted code in main.m file.

 

As you can see I used again square bracket notation to call method cause that’s the only way for us in Objective-C. we can also use square bracket notation for properties like:

c.age = 26

is similar to

[c setAge:26];

Note: Remember we synthesize property so this method is always available for us to use. And for reading property

int age = c.age;

Is similar to

int age = [c age];

Note: I like the dot notation for properties more than square bracket but I also use square notation at some place. It’s up to you. Both method works just fine. For method calling we have one and only one Square bracket method.

Step 12. Now time to hit run again and see what it outputs.

Custom class in objective-c

 

Output is same but now we use method fullname instead of firstname and lastname properties.

Objective-C Special Description Method

Every class that inherits from NSObject contains a special method which is Description that is used when we use %@ in string. Like in NSLog statement in previous example, if we use class object instead of using properties and method to output.

Step 1. Continue working on same project and open main.m file and update highlighted code.

Step 2. Click on run and see the output.

Custom class in objective-c

Step 3. This is not I wanted to print when I use %@ on contact class’s object but I want it to print name and age that is stored in it. For that open contact.m implementation file. And add a new method, which is description. Don’t declare in interface because it came from parent class it will be available for us.

Description method returns fullname fo the contact and age in parenthesis. As you can see that we called self for current object like you call this in java or php.

Now click on run and output will be like this:

Custom class in objective-c

As you can see we get what we want to output and that’s the goal for writing description method for every class.

 

If you like this please follow us on FB Page for more updates.

Series Navigation<< Objective-C Tutorial with xCodeiPhone SDK: Using Existing Objective-C Classes >>

Bookmark Link using: bookmark at folkd