articles

Home / DeveloperSection / Articles / Objective C : Headers, Interfaces, Methods

Objective C : Headers, Interfaces, Methods

Objective C : Headers, Interfaces, Methods

Tarun Kumar4641 03-Jul-2015

Previously we learn the concept of Delegate Objective-C : Programming Language Summary


Objective-C is an object oriented superset of the C language used to create iPhone or iPad apps. Objective-C offers a variety of features found in most object oriented languages such as: inheritance, composition and encapsulation when creating classes.

Messages: The Objective-C model of object-oriented programming is based on message passing to object instances.

 

In Objective-C one does not call a method; one sends a message.
-     Sending the message method to the object pointed to by the
pointer obj would require the following code in C++:   obj->method(argument);

-    In Objective-C, this is written as follows:   [obj  method:argument]; 

Interfaces and implementations: Objective-C requires that the interface and implementation of a class be in separately declared code blocks. By convention, developers place the interface in a header file and the implementation in a code file. The header files, normally suffixed .h, are similar to C header files while the implementation (method) files, normally suffixed .m, can be very similar to C code files.

-  Interface:

 o    The API of the class. Declares what’s going to be in it and defines the class.

o    @interface declares that this is the interface of a class, followed by the class name, followed by a colon, followed by the object that this class inherits. If the object being defined doesn’t inherit a class, it must be defined to inherit NSObject.

§  Example: “@interface SkyScraper : Building”.

§  Notes on inheritance:

§  Objective-C does not support multiple inheritance, but this can be worked around using ‘categories’ and ‘protocols’.

§  A class that is a child of another has all the properties and methods of it’s parent class.

§  You can override inherited methods be redefining a method in the subclass.

§  You can reference the superclass from the subclass using the super keyword. For example, “[super findGreatestSize];”

§  When using the init method of a subclass, it is very wise to make a call to the superclass’s init method, and check that this returns ok using the line, “if ([super init])” then follow code. This ensures that the superclass does everything it should before the subclass adds its bit. This is assigned to self so that the subclass has everything the superclass would already have. This is then checked by the if statement to ensure everything is ok, before the subclass init method initialises subclass specific stuff.

o    This is then followed by a pair of matching curly braces. Instance variables are declared within the curly braces, e.g. “int age = 20;”

o    Methods declarations follow, and are of the format:

§  <method declaration symbol>

§  Either a + or a –, denoting a class method, or an instance method respectively.

§  <return type>

§  Any type, can be void.

§  Must be within brackets.

-   <name>

·    Must be followed by a colon.

-   <optional method parameters>

·   Type first (which must be within brackets), followed by a variable name.

-   <further optional parameters>

·    Objective-C uses infix notation. This means that the name of the method, and it’s arguments, are mixed.

·    You must follow a second (and further) method arguments with the names of arguments.

·   So you must repeat <name> and <optional method parameters> for each argument.

·   For example, a method with three arguments would defined as follows:

§  “- (Circle) generateCircleWithColor: (NSColor) rColor ofSize: (NSSize) rSize withTest: (NSString) rTest;”

§  Notice the types are in brackets.

·    “…” (ellipses) can be used to tell the compiler that the method takes any number of additional arguments, separated by commas. (The stringWithFormat method in NSString uses this).

-    <semicolon>

-   For example:

·   “- (void) setBookColor: (NSColor) rColor;”

-    The word “get” precedes a method conventionally, and is used to mean that this method requires pointers are parameters, so don’t use it for accessor methods (getters).

-  Mutator methods (setters) should proceed with the word “set” conventionally.

o    The interface is ended with the @end notation. 

-     Implementations:

  o    Puts meat on the bones. This is where the actual code for the class is.

o    @implementation declares the start of the implementation section.

o    For each method you wish to code, you must declare which method you wish, then write the code between two curly braces.

o    You don’t finish these methods with a semicolon, as the methods don’t need to be declared – this was done in the interface.

o    You can define a method in the implementation and not in the interface. There’s no private methods, so it can still be accessed, but it won’t be documented in the API (interface).

o    Example:

§  “- (void) setBookColor: (NSColor) rColor { bookColor = rColor; }” 

Instantiation:

  o   Send the new message! e.g. “Class * instance = [Class new];”

 o   The method new allocates memory and initialises a new instance of a class, and is a short hand

 for: “[[Class alloc] init ];” It returns a pointer to this new instance of the class.             o   These methods are all class methods.

   o   The returned object has a retain count of 1 and is not autoreleased (see memory management).  

Header Files in Objective-C :

 #import <Foundation/Foundation.h>

The header file (with the file extension .h) defines the class and everything about it for the world to know.

In this case, the header file acts as the interface to the rest of your program. Your other code will access everything about a class based on what is made available in its interface, including available properties and methods.

One quick thing to point out about import statements: Sometimes you will see the names of things in angle brackets, like this example, and other times you’ll see the names in double quotes, like #import "ViewController.h". Angle brackets tell the compiler to search for the code to import in certain system paths, whereas the double quotes tell it to search within the current project. The idea is to separate the definition of a class from its nitty gritty implementation details. In this case, the header file acts as the interface to the rest of your program. Your other code will access everything about a class based on what is made available in its interface, including available properties and methods.

Let’s take a look at a class that could be used to represent a simple connection to a website. This simple object has one property, a URL, and two methods: “connect” and “canHandleRequest.” The header file might look something like this: UrlConnection.h 

 #import <Foundation/Foundation.h>

@interface UrlConnection : NSObject

@property NSString *url;

- (void)connect;

+ (BOOL)canHandleRequest:(NSString *)type forUrl:(NSString *)url;

@end  

-     [ The first line is what is known as an import statement. This is used to import required files that the code inside this class needs. In this example we are importing the Foundation classes, which includes NSObjects like NSString, NSArray, etc. A class can have many import statements, each on its own line.]

-    (One quick thing to point out about import statements: Sometimes you will see the names of things in angle brackets, like this example, and other times you’ll see the names in double quotes, like #import "PizzaViewController.h". Angle brackets tell the compiler to search for the code to import in certain system paths, whereas the double quotes tell it to search within the current project.) 


Define Class Methods: Methods come in two different forms, class methods and instance methods.

·    Class methods:

-    if you have a class called MathFunctions, you can do this:

+ (int)square:(int)num{

             return num * num;

}

So then the user would call: [MathFunctions square:34];

·         Instance methods:

-        Example:

@interface MyClass : NSObject

     - (void)anInstanceMethod;

@end

They could then be used like so:

MyClass *object = [[MyClass alloc] init];

[object anInstanceMethod]; 

·     If the method returns a result, the name of method must be preceded by the data type returned enclosed in parentheses.

·    If a method does not return a result, then the method must be declared as void.

·    If data needs to be passed through to the method (referred to as arguments), the method name is followed by a colon, the data type in parentheses and a name for the argument.

·    For example, the declaration of a method to set the account number in our example might read as follows:  -(void) setAccountNumber: (long) y;

The method is an instance method so it is preceded by the minus sign. It does not return a result so it is declared as (void). It takes an argument (the account number) of type long so we follow the accountNumber name with a colon (:) specify the argument type (long) and give the argument a name (in this case we simply use y).

·   The following method is intended to return the current value of the account number instance variable (which is of type long): -(long) getAccountNumber;

·   Methods may also be defined to accept more than one argument.

-(void) setAccount: (long) y andBalance: (double) x; 

Basic Syntax for a Class: 

 

Objective C : Headers, Interfaces, Methods

 

Basic Syntax for a Method:

Objective C : Headers, Interfaces, Methods

 

Next, we will learn about  Objective C : object creation method explanations


Updated 03-Feb-2020

Leave Comment

Comments

Liked By