IPhone Key Skills & Concepts

Ratings:
(4)
Views: 338
Banner-Img
Share this blog:

Objective-C-Part One

Key Skills & Concepts

  • Understanding Objective-C classes and objects
  • Understanding an interface and an implementation
  • Understanding simple messaging
  • Understanding alloc and init
  • Managing memory using retain and release
  • Managing memory using autorelease

Iphone applications use Cocoa classes, and these classes use the Objective-C programming language. So you must know Objective-C if you wish to program iPhones. At first glance, Objective-C’s syntax might seem strange and difficult. But don’t worry-the language is easy and its strangeness will give way to an elegance I’m sure you will appreciate. In this and the next chapter you learn enough Objective-C to begin iPhone programming.

CAUTION

If coming from a .NET or Java background, pay particular attention to the sections on memory management. Unlike these languages, memory management is not automatic on the iPhone. You must manage memory manually.

Objective-C Classes and Objects

Objective-C classes are the same as classes in any other object-oriented programming language. A class encapsulates both state (properties) and behavior (methods), and forms an object-oriented program’s basic building blocks. An object-oriented application functions by objects sending messages between each other. For instance, in a typical Java command-line application, you begin the program by calling a static method called main in a class. This main method instantiates one or more objects, and the application’s remaining functionality consists of messages between those objects instantiated in the main method, as well as any objects they might in turn instantiate.  

Class Interface and Implementation:

Objective-C separates a class into an interface and an implementation. An interface declares instance variables and methods. It is a standard C header file and doesn’t provide any method implementations. The implementation contains the class’s method implementations. It is a file with its own .m extension rather than a .c extension.  

Generating an Objective-C Class’s Interface and Implementation:

  1. Create a new View-based Application and name it Chap
  2. In Groups & Files, right-click Classes and select Add | New Group from the pop-up

Name the group Objective-C.

  1. Right-click the newly created Objective-C folder and select Add | New File from the pop- up From the New File dialog, highlight Cocoa Touch Class and select Objective-C class. Ensure the Subclass says NSObject (Figure 3-1). Click Next.
  2. On the next dialogue screen, name the class Simple. Be certain to also check the checkbox asking if you wish to generate a header file for the class.The template generated Simple for you, writing its interface in Simple.h and its implementation in Simple.m.

   Listing 3-1 Objective-C interface #import <Foundation/Foundation.h> @interface Simple : NSObject { } @end Listing 3-2 Objective-C implementation #import "Simple.h" @implementation Simple @end

The @interface and @implementation Compiler Directives

In Simple.h, note the @interface compiler directive. In the Simple.m file, note the @implementation compiler directive. These directives distinguish a class’s interface from its implementation. Code within the @interface and @end compiler directives in Simple.h comprise Simple’s interface, while code within the @implementation and @end compiler directives comprise Simple’s implementation.   1 Slide1 Figure 3-1 selecting a new Objective-C class using Xcode’s New File dialog  

Method Declaration and Definition

You declare a class’s methods and instance variables in its interface. You define a class’s methods and instance variables in its implementation. Declaring a method means you tell the compiler that a class will have a method, with a certain signature, but you don’t provide the actual code for the method. For instance, consider the following method declaration. - (void) sayHello: (NSString*) name; The declaration tells the compiler to expect a method called sayHello that returns nothing (void) and takes an NSString as an argument. The declaration says nothing about the method’s content. You provide the compiler with a method’s implementation by defining the method. Defining a method means you provide a method declaration’s actual behavior, or its implementation. For instance, the sayHello method in Listing 3-3 provides the sayHello method declaration’s behavior. A simple Objective-C method implementation - (void) sayHello: (NSString*) name { NSMutableString *message = [[NSMutableString alloc] initWithString: @"Hello there "]; [message appendString:name]; NSLog(message); [message release]; }

Adding sayHello to the Simple Class

  1. Open the last section’s project, Add the sayHello method from Listing 3-3 to Simple.m (Listing 3-4). Don’t forget to add the method’s declaration to Simple.h (Listing 3-5).
  2. Open m and import Simple. Then in main, create a Simple instance and call it sayHello method (Listing 3-6).
  3. Build and run the program, and the hello message appears in the debugger console.

 Simple.m modified to declare sayHello #import "Simple.h" @implementation Simple -    (void) sayHello: (NSString *) name { NSMutableString *message = [[NSMutableString alloc] initWithString:@"Hello there "]; [message appendString:name]; NSLog(message); [message release]; } @end Simple.h modified to declare sayHello #import <Foundation/Foundation.h> @interface Simple : NSObject { } -(void) sayHello: (NSString *) name; @end The file main.h modified to call the sayHello method #import <UIKit/UIKit.h> #import "Simple.h" int main(int argc, char *argv[]) { NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; Simple * mySimple = [[Simple alloc] init]; [mySimple sayHello:@"James"]; [mySimple release]; int retVal = UIApplicationMain(argc, argv, nil, nil); [pool release]; return retVal; } Interface Anatomy A class’s interface consists of import statements, a class declaration, any instance variables, and method signatures. Review Simple’s interface in the Simple.h file. Objective-C classes import or include other libraries and headers just like C (just a reminder, always use import, as this assures you won’t include the header file twice). The following line declares to the compiler an Objective-C class named Simple that extends NSObject. Slide2 An Objective-C interface summary An opening and closing brace follows the class declaration. Instance variables go between these braces. Below the closing brace, you add class method declarations. Following any method declarations, the interface ends with the @end directive, which signifies the interface’s end. Summarizes an Objective-C interface’s anatomy.

Implementation Anatomy

An interface is only half an Objective-C class, though. A class’s implementation is as important as its interface. Review Simple’s implementation in the Simple.m file. This file begins by importing the class’s interface. Simple’s implementation then begins with the @implementation compiler directive. @implementation Simple Simple’s implementation ends with the @end compiler directive. Method definitions go between the two directives. Figure 3-3 summarizes an Objective-C class implementation.

Public, Private, and Protected Instance Variables

Class’s can set instance variables to be private, protected, public, and package. You use the compiler directives @private, @protected, @public, and @package to declare instance variable visibility. The private directive ensures variables marked as private are only visible   Slide3   An Objective-C implementation summaryto the class that declares the instance variable. The protected directive ensures protected variables are only visible to the declaring class and its descendants. The public directive allows any class access to the public variables. The package directive is applicable only to 64-bit systems, and is a little more involved than the other directives. Refer to Apple’s documentation for more information on the package directive.   Consider the interface code snippet Public and private methods @public NSString* groupName; int intGroupSize; @private NSString* otherGroupName; int intOtherGroupSize; In this interface declaration, the instance variables groupName and intGroupSize are public, while otherGroupName and intOtherGroupSize are private.    

You liked the article?

Like: 0

Vote for difficulty

Current difficulty (Avg): Medium

EasyMediumHardDifficultExpert
IMPROVE ARTICLEReport Issue

About Author

Authorlogo
Name
TekSlate
Author Bio

TekSlate is the best online training provider in delivering world-class IT skills to individuals and corporates from all parts of the globe. We are proven experts in accumulating every need of an IT skills upgrade aspirant and have delivered excellent services. We aim to bring you all the essentials to learn and master new technologies in the market with our articles, blogs, and videos. Build your career success with us, enhancing most in-demand skills in the market.

Stay Updated
Get stories of change makers and innovators from the startup ecosystem in your inbox