Objective-C – Inheritance

Objective-C Inheritance ”; Previous Next One of the most important concepts in object-oriented programming is that of inheritance. Inheritance allows us to define a class in terms of another class which makes it easier to create and maintain an application. This also provides an opportunity to reuse the code functionality and fast implementation time. When creating a class, instead of writing completely new data members and member functions, the programmer can designate that the new class should inherit the members of an existing class. This existing class is called the base class, and the new class is referred to as the derived class. The idea of inheritance implements the is a relationship. For example, mammal IS-A animal, dog IS-A mammal, hence dog IS-A animal as well and so on. Base & Derived Classes Objective-C allows only multilevel inheritance, i.e., it can have only one base class but allows multilevel inheritance. All classes in Objective-C is derived from the superclass NSObject. @interface derived-class: base-class Consider a base class Person and its derived class Employee as follows − Live Demo #import <Foundation/Foundation.h> @interface Person : NSObject { NSString *personName; NSInteger personAge; } – (id)initWithName:(NSString *)name andAge:(NSInteger)age; – (void)print; @end @implementation Person – (id)initWithName:(NSString *)name andAge:(NSInteger)age { personName = name; personAge = age; return self; } – (void)print { NSLog(@”Name: %@”, personName); NSLog(@”Age: %ld”, personAge); } @end @interface Employee : Person { NSString *employeeEducation; } – (id)initWithName:(NSString *)name andAge:(NSInteger)age andEducation:(NSString *)education; – (void)print; @end @implementation Employee – (id)initWithName:(NSString *)name andAge:(NSInteger)age andEducation: (NSString *)education { personName = name; personAge = age; employeeEducation = education; return self; } – (void)print { NSLog(@”Name: %@”, personName); NSLog(@”Age: %ld”, personAge); NSLog(@”Education: %@”, employeeEducation); } @end int main(int argc, const char * argv[]) { NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; NSLog(@”Base class Person Object”); Person *person = [[Person alloc]initWithName:@”Raj” andAge:5]; [person print]; NSLog(@”Inherited Class Employee Object”); Employee *employee = [[Employee alloc]initWithName:@”Raj” andAge:5 andEducation:@”MBA”]; [employee print]; [pool drain]; return 0; } When the above code is compiled and executed, it produces the following result − 2013-09-22 21:20:09.842 Inheritance[349:303] Base class Person Object 2013-09-22 21:20:09.844 Inheritance[349:303] Name: Raj 2013-09-22 21:20:09.844 Inheritance[349:303] Age: 5 2013-09-22 21:20:09.845 Inheritance[349:303] Inherited Class Employee Object 2013-09-22 21:20:09.845 Inheritance[349:303] Name: Raj 2013-09-22 21:20:09.846 Inheritance[349:303] Age: 5 2013-09-22 21:20:09.846 Inheritance[349:303] Education: MBA Access Control and Inheritance A derived class can access all the private members of its base class if it”s defined in the interface class, but it cannot access private members that are defined in the implementation file. We can summarize the different access types according to who can access them in the following way − A derived class inherits all base class methods and variables with the following exceptions − Variables declared in implementation file with the help of extensions is not accessible. Methods declared in implementation file with the help of extensions is not accessible. In case the inherited class implements the method in base class, then the method in derived class is executed. Print Page Previous Next Advertisements ”;

Objective-C – Quick Guide

Objective-C Quick Guide ”; Previous Next Objective-C Overview Objective-C is general-purpose language that is developed on top of C Programming language by adding features of Small Talk programming language making it an object-oriented language. It is primarily used in developing iOS and Mac OS X operating systems as well as its applications. Initially, Objective-C was developed by NeXT for its NeXTSTEP OS from whom it was taken over by Apple for its iOS and Mac OS X. Object-Oriented Programming Fully supports object-oriented programming, including the four pillars of object-oriented development − Encapsulation Data hiding Inheritance Polymorphism Example Code Live Demo #import <Foundation/Foundation.h> int main (int argc, const char * argv[]) { NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; NSLog (@”hello world”); [pool drain]; return 0; } Foundation Framework Foundation Framework provides large set of features and they are listed below. It includes a list of extended datatypes like NSArray, NSDictionary, NSSet and so on. It consists of a rich set of functions manipulating files, strings, etc. It provides features for URL handling, utilities like date formatting, data handling, error handling, etc. Learning Objective-C The most important thing to do when learning Objective-C is to focus on concepts and not get lost in language technical details. The purpose of learning a programming language is to become a better programmer; that is, to become more effective at designing and implementing new systems and at maintaining old ones. Use of Objective-C Objective-C, as mentioned earlier, is used in iOS and Mac OS X. It has large base of iOS users and largely increasing Mac OS X users. And since Apple focuses on quality first and its wonderful for those who started learning Objective-C. Objective-C Environment Setup Local Environment Setup If you are still willing to set up your environment for Objective-C programming language, you need the following two softwares available on your computer, (a) Text Editor and (b) The GCC Compiler. Text Editor This will be used to type your program. Examples of few editors include Windows Notepad, OS Edit command, Brief, Epsilon, EMACS, and vim or vi. Name and version of text editor can vary on different operating systems. For example, Notepad will be used on Windows, and vim or vi can be used on windows as well as Linux or UNIX. The files you create with your editor are called source files and contain program source code. The source files for Objective-C programs are typically named with the extension “.m“. Before starting your programming, make sure you have one text editor in place and you have enough experience to write a computer program, save it in a file, compile it and finally execute it. The GCC Compiler The source code written in source file is the human readable source for your program. It needs to be “compiled” to turn into machine language, so that your CPU can actually execute the program as per instructions given. This GCC compiler will be used to compile your source code into final executable program. I assume you have basic knowledge about a programming language compiler. GCC compiler is available for free on various platforms and the procedure to set up on various platforms is explained below. Installation on UNIX/Linux The initial step is install gcc along with gcc Objective-C package. This is done by − $ su – $ yum install gcc $ yum install gcc-objc The next step is to set up package dependencies using following command − $ yum install make libpng libpng-devel libtiff libtiff-devel libobjc libxml2 libxml2-devel libX11-devel libXt-devel libjpeg libjpeg-devel In order to get full features of Objective-C, download and install GNUStep. Now, we need to switch to the downloaded folder and unpack the file by − $ tar xvfz gnustep-startup-.tar.gz Now, we need to switch to the folder gnustep-startup that gets created using − $ cd gnustep-startup-<version> Next, we need to configure the build process − $ ./configure Then, we can build by − $ make We need to finally set up the environment by − $ . /usr/GNUstep/System/Library/Makefiles/GNUstep.sh We have a helloWorld.m Objective-C as follows − #import <Foundation/Foundation.h> int main (int argc, const char * argv[]) { NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; NSLog (@”hello world”); [pool drain]; return 0; } Now, we can compile and run a Objective-C file say helloWorld.m by switching to folder containing the file using cd and then using the following steps − $ gcc `gnustep-config –objc-flags` -L/usr/GNUstep/Local/Library/Libraries -lgnustep-base helloWorld.m -o helloWorld $ ./helloWorld We can see the following output − 2013-09-07 10:48:39.772 tutorialsPoint[12906] hello world Installation on Mac OS If you use Mac OS X, the easiest way to obtain GCC is to download the Xcode development environment from Apple”s web site and follow the simple installation instructions. Once you have Xcode set up, you will be able to use GNU compiler for C/C++. Xcode is currently available at developer.apple.com/technologies/tools/. Installation on Windows In order to run Objective-C program on windows, we need to install MinGW and GNUStep Core. Both are available at https://www.gnu.org/software/gnustep/windows/installer.html. First, we need to install the MSYS/MinGW System package. Then, we need to install the GNUstep Core package. Both of which provide a windows installer, which is self-explanatory. Then to use Objective-C and GNUstep by selecting Start -> All Programs -> GNUstep -> Shell Switch to the folder containing helloWorld.m We can compile the program by using − $ gcc `gnustep-config –objc-flags` -L /GNUstep/System/Library/Libraries hello.m -o hello -lgnustep-base -lobjc We can run the program by using − ./hello.exe We get the following output − 2013-09-07 10:48:39.772 tutorialsPoint[1200] hello world Objective-C Program Structure Before we study basic building blocks of the Objective-C programming language, let us look a bare minimum Objective-C program structure so that we can take it as a reference in upcoming chapters. Objective-C Hello World Example A Objective-C program basically consists of the following parts − Preprocessor Commands Interface Implementation Method Variables Statements & Expressions Comments Let us look at a simple code that would print the words “Hello World” − Live

Objective-C – Constants

Objective-C Constants ”; Previous Next The constants refer to fixed values that the program may not alter during its execution. These fixed values are also called literals. Constants can be of any of the basic data types like an integer constant, a floating constant, a character constant, or a string literal. There are also enumeration constants as well. The constants are treated just like regular variables except that their values cannot be modified after their definition. Integer Literals An integer literal can be a decimal, octal, or hexadecimal constant. A prefix specifies the base or radix: 0x or 0X for hexadecimal, 0 for octal, and nothing for decimal. An integer literal can also have a suffix that is a combination of U and L, for unsigned and long, respectively. The suffix can be uppercase or lowercase and can be in any order. Here are some examples of integer literals − 212 /* Legal */ 215u /* Legal */ 0xFeeL /* Legal */ 078 /* Illegal: 8 is not an octal digit */ 032UU /* Illegal: cannot repeat a suffix */ Following are other examples of various types of Integer literals − 85 /* decimal */ 0213 /* octal */ 0x4b /* hexadecimal */ 30 /* int */ 30u /* unsigned int */ 30l /* long */ 30ul /* unsigned long */ Floating-point Literals A floating-point literal has an integer part, a decimal point, a fractional part, and an exponent part. You can represent floating point literals either in decimal form or exponential form. While representing using decimal form, you must include the decimal point, the exponent, or both and while representing using exponential form, you must include the integer part, the fractional part, or both. The signed exponent is introduced by e or E. Here are some examples of floating-point literals − 3.14159 /* Legal */ 314159E-5L /* Legal */ 510E /* Illegal: incomplete exponent */ 210f /* Illegal: no decimal or exponent */ .e55 /* Illegal: missing integer or fraction */ Character Constants Character literals are enclosed in single quotes e.g., ”x” and can be stored in a simple variable of char type. A character literal can be a plain character (e.g., ”x”), an escape sequence (e.g., ”t”), or a universal character (e.g., ”u02C0”). There are certain characters in C when they are proceeded by a backslash they will have special meaning and they are used to represent like newline (n) or tab (t). Here, you have a list of some of such escape sequence codes − Escape sequence Meaning \ character ” ” character “ ” character ? ? character a Alert or bell b Backspace f Form feed n Newline r Carriage return t Horizontal tab v Vertical tab ooo Octal number of one to three digits xhh . . . Hexadecimal number of one or more digits Following is the example to show few escape sequence characters − Live Demo #import <Foundation/Foundation.h> int main() { NSLog(@”HellotWorldnn”); return 0; } When the above code is compiled and executed, it produces the following result − 2013-09-07 22:17:17.923 demo[17871] Hello World String Literals String literals or constants are enclosed in double quotes “”. A string contains characters that are similar to character literals: plain characters, escape sequences, and universal characters. You can break a long line into multiple lines using string literals and separating them using whitespaces. Here are some examples of string literals. All the three forms are identical strings. “hello, dear” “hello, dear” “hello, ” “d” “ear” Defining Constants There are two simple ways in C to define constants − Using #define preprocessor. Using const keyword. The #define Preprocessor Following is the form to use #define preprocessor to define a constant − #define identifier value Following example explains it in detail − Live Demo #import <Foundation/Foundation.h> #define LENGTH 10 #define WIDTH 5 #define NEWLINE ”n” int main() { int area; area = LENGTH * WIDTH; NSLog(@”value of area : %d”, area); NSLog(@”%c”, NEWLINE); return 0; } When the above code is compiled and executed, it produces the following result − 2013-09-07 22:18:16.637 demo[21460] value of area : 50 2013-09-07 22:18:16.638 demo[21460] The const Keyword You can use const prefix to declare constants with a specific type as follows − const type variable = value; Following example explains it in detail − Live Demo #import <Foundation/Foundation.h> int main() { const int LENGTH = 10; const int WIDTH = 5; const char NEWLINE = ”n”; int area; area = LENGTH * WIDTH; NSLog(@”value of area : %d”, area); NSLog(@”%c”, NEWLINE); return 0; } When the above code is compiled and executed, it produces the following result − 2013-09-07 22:19:24.780 demo[25621] value of area : 50 2013-09-07 22:19:24.781 demo[25621] Note that it is a good programming practice to define constants in CAPITALS. Print Page Previous Next Advertisements ”;

Objective-C – Pointers

Objective-C Pointers ”; Previous Next Pointers in Objective-C are easy and fun to learn. Some Objective-C programming tasks are performed more easily with pointers, and other tasks, such as dynamic memory allocation, cannot be performed without using pointers. So it becomes necessary to learn pointers to become a perfect Objective-C programmer. Let”s start learning them in simple and easy steps. As you know, every variable is a memory location and every memory location has its address defined which can be accessed using ampersand (&) operator, which denotes an address in memory. Consider the following example, which will print the address of the variables defined − Live Demo #import <Foundation/Foundation.h> int main () { int var1; char var2[10]; NSLog(@”Address of var1 variable: %xn”, &var1 ); NSLog(@”Address of var2 variable: %xn”, &var2 ); return 0; } When the above code is compiled and executed, it produces the result something as follows − 2013-09-13 03:18:45.727 demo[17552] Address of var1 variable: 1c0843fc 2013-09-13 03:18:45.728 demo[17552] Address of var2 variable: 1c0843f0 So, you understood what is memory address and how to access it, so base of the concept is over. Now let us see what is a pointer. What Are Pointers? A pointer is a variable whose value is the address of another variable, i.e., direct address of the memory location. Like any variable or constant, you must declare a pointer before you can use it to store any variable address. The general form of a pointer variable declaration is − type *var-name; Here, type is the pointer”s base type; it must be a valid Objective-C data type and var-name is the name of the pointer variable. The asterisk * you used to declare a pointer is the same asterisk that you use for multiplication. However, in this statement the asterisk is being used to designate a variable as a pointer. Following are the valid pointer declaration − int *ip; /* pointer to an integer */ double *dp; /* pointer to a double */ float *fp; /* pointer to a float */ char *ch /* pointer to a character */ The actual data type of the value of all pointers, whether integer, float, character, or otherwise, is the same, a long hexadecimal number that represents a memory address. The only difference between pointers of different data types is the data type of the variable or constant that the pointer points to. How to use Pointers? There are few important operations, which we will do with the help of pointers very frequently. (a) we define a pointer variable, (b) assign the address of a variable to a pointer, and (c) finally access the value at the address available in the pointer variable. This is done by using unary operator * that returns the value of the variable located at the address specified by its operand. Following example makes use of these operations − Live Demo #import <Foundation/Foundation.h> int main () { int var = 20; /* actual variable declaration */ int *ip; /* pointer variable declaration */ ip = &var; /* store address of var in pointer variable*/ NSLog(@”Address of var variable: %xn”, &var ); /* address stored in pointer variable */ NSLog(@”Address stored in ip variable: %xn”, ip ); /* access the value using the pointer */ NSLog(@”Value of *ip variable: %dn”, *ip ); return 0; } When the above code is compiled and executed, it produces the result something as follows − 2013-09-13 03:20:21.873 demo[24179] Address of var variable: 337ed41c 2013-09-13 03:20:21.873 demo[24179] Address stored in ip variable: 337ed41c 2013-09-13 03:20:21.874 demo[24179] Value of *ip variable: 20 NULL Pointers in Objective-C It is always a good practice to assign a NULL value to a pointer variable in case you do not have exact address to be assigned. This is done at the time of variable declaration. A pointer that is assigned NULL is called a null pointer. The NULL pointer is a constant with a value of zero defined in several standard libraries. Consider the following program − Live Demo #import <Foundation/Foundation.h> int main () { int *ptr = NULL; NSLog(@”The value of ptr is : %xn”, ptr ); return 0; } When the above code is compiled and executed, it produces the following result − 2013-09-13 03:21:19.447 demo[28027] The value of ptr is : 0 On most of the operating systems, programs are not permitted to access memory at address 0 because that memory is reserved by the operating system. However, the memory address 0 has special significance; it signals that the pointer is not intended to point to an accessible memory location. But by convention, if a pointer contains the null (zero) value, it is assumed to point to nothing. To check for a null pointer, you can use an if statement as follows − if(ptr) /* succeeds if p is not null */ if(!ptr) /* succeeds if p is null */ Objective-C Pointers in Detail Pointers have many but easy concepts and they are very important to Objective-C programming. There are following few important pointer concepts, which should be clear to a Objective-C programmer − Sr.No. Concept & Description 1 Objective-C – Pointer arithmetic There are four arithmetic operators that can be used on pointers: ++, –, +, – 2 Objective-C – Array of pointers You can define arrays to hold a number of pointers. 3 Objective-C – Pointer to pointer Objective-C allows you to have pointer on a pointer and so on. 4 Passing pointers to functions in Objective-C Passing an argument by reference or by address both enable the passed argument to be changed in the calling function by the called function. 5 Return pointer from functions in Objective-C Objective-C allows a function to return a pointer to local variable, static variable and dynamically allocated memory as well. Print Page Previous Next Advertisements ”;

Objective-C – Structures

Objective-C Structures ”; Previous Next Objective-C arrays allow you to define type of variables that can hold several data items of the same kind but structure is another user-defined data type available in Objective-C programming which allows you to combine data items of different kinds. Structures are used to represent a record, Suppose you want to keep track of your books in a library. You might want to track the following attributes about each book − Title Author Subject Book ID Defining a Structure To define a structure, you must use the struct statement. The struct statement defines a new data type, with more than one member for your program. The format of the struct statement is shown below − struct [structure tag] { member definition; member definition; … member definition; } [one or more structure variables]; The structure tag is optional and each member definition is a normal variable definition, such as int i; or float f; or any other valid variable definition. At the end of the structure”s definition, before the final semicolon, you can specify one or more structure variables but it is optional. Here is the way you would declare the Book structure − struct Books { NSString *title; NSString *author; NSString *subject; int book_id; } book; Accessing Structure Members To access any member of a structure, we use the member access operator (.). The member access operator is coded as a period between the structure variable name and the structure member that we wish to access. You would use struct keyword to define variables of structure type. Following is the example to explain usage of structure − Live Demo #import <Foundation/Foundation.h> struct Books { NSString *title; NSString *author; NSString *subject; int book_id; }; int main() { struct Books Book1; /* Declare Book1 of type Book */ struct Books Book2; /* Declare Book2 of type Book */ /* book 1 specification */ Book1.title = @”Objective-C Programming”; Book1.author = @”Nuha Ali”; Book1.subject = @”Objective-C Programming Tutorial”; Book1.book_id = 6495407; /* book 2 specification */ Book2.title = @”Telecom Billing”; Book2.author = @”Zara Ali”; Book2.subject = @”Telecom Billing Tutorial”; Book2.book_id = 6495700; /* print Book1 info */ NSLog(@”Book 1 title : %@n”, Book1.title); NSLog(@”Book 1 author : %@n”, Book1.author); NSLog(@”Book 1 subject : %@n”, Book1.subject); NSLog(@”Book 1 book_id : %dn”, Book1.book_id); /* print Book2 info */ NSLog(@”Book 2 title : %@n”, Book2.title); NSLog(@”Book 2 author : %@n”, Book2.author); NSLog(@”Book 2 subject : %@n”, Book2.subject); NSLog(@”Book 2 book_id : %dn”, Book2.book_id); return 0; } When the above code is compiled and executed, it produces the following result − 2013-09-14 04:20:07.947 demo[20591] Book 1 title : Objective-C Programming 2013-09-14 04:20:07.947 demo[20591] Book 1 author : Nuha Ali 2013-09-14 04:20:07.947 demo[20591] Book 1 subject : Objective-C Programming Tutorial 2013-09-14 04:20:07.947 demo[20591] Book 1 book_id : 6495407 2013-09-14 04:20:07.947 demo[20591] Book 2 title : Telecom Billing 2013-09-14 04:20:07.947 demo[20591] Book 2 author : Zara Ali 2013-09-14 04:20:07.947 demo[20591] Book 2 subject : Telecom Billing Tutorial 2013-09-14 04:20:07.947 demo[20591] Book 2 book_id : 6495700 Structures as Function Arguments You can pass a structure as a function argument in very similar way as you pass any other variable or pointer. You would access structure variables in the similar way as you have accessed in the above example − Live Demo #import <Foundation/Foundation.h> struct Books { NSString *title; NSString *author; NSString *subject; int book_id; }; @interface SampleClass:NSObject /* function declaration */ – (void) printBook:( struct Books) book ; @end @implementation SampleClass – (void) printBook:( struct Books) book { NSLog(@”Book title : %@n”, book.title); NSLog(@”Book author : %@n”, book.author); NSLog(@”Book subject : %@n”, book.subject); NSLog(@”Book book_id : %dn”, book.book_id); } @end int main() { struct Books Book1; /* Declare Book1 of type Book */ struct Books Book2; /* Declare Book2 of type Book */ /* book 1 specification */ Book1.title = @”Objective-C Programming”; Book1.author = @”Nuha Ali”; Book1.subject = @”Objective-C Programming Tutorial”; Book1.book_id = 6495407; /* book 2 specification */ Book2.title = @”Telecom Billing”; Book2.author = @”Zara Ali”; Book2.subject = @”Telecom Billing Tutorial”; Book2.book_id = 6495700; SampleClass *sampleClass = [[SampleClass alloc]init]; /* print Book1 info */ [sampleClass printBook: Book1]; /* Print Book2 info */ [sampleClass printBook: Book2]; return 0; } When the above code is compiled and executed, it produces the following result − 2013-09-14 04:34:45.725 demo[8060] Book title : Objective-C Programming 2013-09-14 04:34:45.725 demo[8060] Book author : Nuha Ali 2013-09-14 04:34:45.725 demo[8060] Book subject : Objective-C Programming Tutorial 2013-09-14 04:34:45.725 demo[8060] Book book_id : 6495407 2013-09-14 04:34:45.725 demo[8060] Book title : Telecom Billing 2013-09-14 04:34:45.725 demo[8060] Book author : Zara Ali 2013-09-14 04:34:45.725 demo[8060] Book subject : Telecom Billing Tutorial 2013-09-14 04:34:45.725 demo[8060] Book book_id : 6495700 Pointers to Structures You can define pointers to structures in very similar way as you define pointer to any other variable as follows − struct Books *struct_pointer; Now, you can store the address of a structure variable in the above-defined pointer variable. To find the address of a structure variable, place the & operator before the structure”s name as follows − struct_pointer = &Book1; To access the members of a structure using a pointer to that structure, you must use the -> operator as follows − struct_pointer->title; Let us re-write above example using structure pointer, hope this will be easy for you to understand the concept − Live Demo #import <Foundation/Foundation.h> struct Books { NSString *title; NSString *author; NSString *subject; int book_id; }; @interface SampleClass:NSObject /* function declaration */ – (void) printBook:( struct Books *) book ; @end @implementation SampleClass – (void) printBook:( struct Books *) book { NSLog(@”Book title : %@n”, book->title); NSLog(@”Book author : %@n”, book->author); NSLog(@”Book subject : %@n”, book->subject); NSLog(@”Book book_id : %dn”, book->book_id); } @end int main() { struct Books Book1; /* Declare Book1 of type Book */ struct Books Book2; /* Declare Book2 of type Book */ /* book 1 specification */ Book1.title = @”Objective-C Programming”; Book1.author = @”Nuha Ali”; Book1.subject = @”Objective-C Programming Tutorial”; Book1.book_id = 6495407; /* book 2 specification */ Book2.title = @”Telecom Billing”; Book2.author =

Objective-C – Variables

Objective-C Variables ”; Previous Next A variable is nothing but a name given to a storage area that our programs can manipulate. Each variable in Objective-C has a specific type, which determines the size and layout of the variable”s memory; the range of values that can be stored within that memory; and the set of operations that can be applied to the variable. The name of a variable can be composed of letters, digits, and the underscore character. It must begin with either a letter or an underscore. Upper and lowercase letters are distinct because Objective-C is case-sensitive. Based on the basic types explained in previous chapter, there will be the following basic variable types − Sr.No. Type & Description 1 char Typically a single octet (one byte). This is an integer type. 2 int The most natural size of integer for the machine. 3 float A single-precision floating point value. 4 double A double-precision floating point value. 5 void Represents the absence of type. Objective-C programming language also allows to define various other types of variables, which we will cover in subsequent chapters like Enumeration, Pointer, Array, Structure, Union, etc. For this chapter, let us study only basic variable types. Variable Definition in Objective-C A variable definition means to tell the compiler where and how much to create the storage for the variable. A variable definition specifies a data type and contains a list of one or more variables of that type as follows − type variable_list; Here, type must be a valid Objective-C data type including char, w_char, int, float, double, bool or any user-defined object, etc., and variable_list may consist of one or more identifier names separated by commas. Some valid declarations are shown here − int i, j, k; char c, ch; float f, salary; double d; The line int i, j, k; both declares and defines the variables i, j and k; which instructs the compiler to create variables named i, j and k of type int. Variables can be initialized (assigned an initial value) in their declaration. The initializer consists of an equal sign followed by a constant expression as follows − type variable_name = value; Some examples are − extern int d = 3, f = 5; // declaration of d and f. int d = 3, f = 5; // definition and initializing d and f. byte z = 22; // definition and initializes z. char x = ”x”; // the variable x has the value ”x”. For definition without an initializer: variables with static storage duration are implicitly initialized with NULL (all bytes have the value 0); the initial value of all other variables is undefined. Variable Declaration in Objective-C A variable declaration provides assurance to the compiler that there is one variable existing with the given type and name so that compiler proceed for further compilation without needing complete detail about the variable. A variable declaration has its meaning at the time of compilation only, compiler needs actual variable declaration at the time of linking of the program. A variable declaration is useful when you are using multiple files and you define your variable in one of the files, which will be available at the time of linking of the program. You will use extern keyword to declare a variable at any place. Though you can declare a variable multiple times in your Objective-C program but it can be defined only once in a file, a function or a block of code. Example Try the following example, where variables have been declared at the top, but they have been defined and initialized inside the main function − Live Demo #import <Foundation/Foundation.h> // Variable declaration: extern int a, b; extern int c; extern float f; int main () { /* variable definition: */ int a, b; int c; float f; /* actual initialization */ a = 10; b = 20; c = a + b; NSLog(@”value of c : %d n”, c); f = 70.0/3.0; NSLog(@”value of f : %f n”, f); return 0; } When the above code is compiled and executed, it produces the following result − 2013-09-07 22:43:31.695 demo[14019] value of c : 30 2013-09-07 22:43:31.695 demo[14019] value of f : 23.333334 Same concept applies on function declaration where you provide a function name at the time of its declaration and its actual definition can be given anywhere else. In the following example, it”s explained using C function and as you know Objective-C supports C style functions also − // function declaration int func(); int main() { // function call int i = func(); } // function definition int func() { return 0; } Lvalues and Rvalues in Objective-C There are two kinds of expressions in Objective-C − lvalue − Expressions that refer to a memory location is called “lvalue” expression. An lvalue may appear as either the left-hand or right-hand side of an assignment. rvalue − The term rvalue refers to a data value that is stored at some address in memory. An rvalue is an expression that cannot have a value assigned to it which means an rvalue may appear on the right- but not left-hand side of an assignment. Variables are lvalues and so may appear on the left-hand side of an assignment. Numeric literals are rvalues and so may not be assigned and can not appear on the left-hand side. Following is a valid statement − int g = 20; But following is not a valid statement and would generate compile-time error − 10 = 20; Print Page Previous Next Advertisements ”;

Objective-C – Basic Syntax

Objective-C Basic Syntax ”; Previous Next You have seen a basic structure of Objective-C program, so it will be easy to understand other basic building blocks of the Objective-C programming language. Tokens in Objective-C A Objective-C program consists of various tokens and a token is either a keyword, an identifier, a constant, a string literal, or a symbol. For example, the following Objective-C statement consists of six tokens − NSLog(@”Hello, World! n”); The individual tokens are − NSLog @ ( “Hello, World! n” ) ; Semicolons ; In Objective-C program, the semicolon is a statement terminator. That is, each individual statement must be ended with a semicolon. It indicates the end of one logical entity. For example, following are two different statements − NSLog(@”Hello, World! n”); return 0; Comments Comments are like helping text in your Objective-C program and they are ignored by the compiler. They start with /* and terminate with the characters */ as shown below − /* my first program in Objective-C */ You can not have comments with in comments and they do not occur within a string or character literals. Identifiers An Objective-C identifier is a name used to identify a variable, function, or any other user-defined item. An identifier starts with a letter A to Z or a to z or an underscore _ followed by zero or more letters, underscores, and digits (0 to 9). Objective-C does not allow punctuation characters such as @, $, and % within identifiers. Objective-C is a case-sensitive programming language. Thus, Manpower and manpower are two different identifiers in Objective-C. Here are some examples of acceptable identifiers − mohd zara abc move_name a_123 myname50 _temp j a23b9 retVal Keywords The following list shows few of the reserved words in Objective-C. These reserved words may not be used as constant or variable or any other identifier names. auto else long switch break enum register typedef case extern return union char float short unsigned const for signed void continue goto sizeof volatile default if static while do int struct _Packed double protocol interface implementation NSObject NSInteger NSNumber CGFloat property nonatomic; retain strong weak unsafe_unretained; readwrite readonly Whitespace in Objective-C A line containing only whitespace, possibly with a comment, is known as a blank line, and an Objective-C compiler totally ignores it. Whitespace is the term used in Objective-C to describe blanks, tabs, newline characters and comments. Whitespace separates one part of a statement from another and enables the compiler to identify where one element in a statement, such as int, ends and the next element begins. Therefore, in the following statement − int age; There must be at least one whitespace character (usually a space) between int and age for the compiler to be able to distinguish them. On the other hand, in the following statement, fruit = apples + oranges; // get the total fruit No whitespace characters are necessary between fruit and =, or between = and apples, although you are free to include some if you wish for readability purpose. Print Page Previous Next Advertisements ”;

Objective-C – Decision Making

Objective-C Decision Making ”; Previous Next Decision making structures require that the programmer specify one or more conditions to be evaluated or tested by the program, along with a statement or statements to be executed if the condition is determined to be true, and optionally, other statements to be executed if the condition is determined to be false. Following is the general form of a typical decision making structure found in most of the programming languages − Objective-C programming language assumes any non-zero and non-null values as true, and if it is either zero or null, then it is assumed as false value. Objective-C programming language provides following types of decision making statements. Click the following links to check their details − Sr.No. Statement & Description 1 if statement An if statement consists of a boolean expression followed by one or more statements. 2 if…else statement An if statement can be followed by an optional else statement, which executes when the boolean expression is false. 3 nested if statements You can use one if or else if statement inside another if or else if statement(s). 4 switch statement A switch statement allows a variable to be tested for equality against a list of values. 5 nested switch statements You can use one switch statement inside another switch statement(s). The ? : Operator We have covered conditional operator ? : in previous chapter which can be used to replace if…else statements. It has the following general form − Exp1 ? Exp2 : Exp3; Where Exp1, Exp2, and Exp3 are expressions. Notice the use and placement of the colon. The value of a ? expression is determined like this: Exp1 is evaluated. If it is true, then Exp2 is evaluated and becomes the value of the entire ? expression. If Exp1 is false, then Exp3 is evaluated and its value becomes the value of the expression. Print Page Previous Next Advertisements ”;

Objective-C – Strings

Objective-C Strings ”; Previous Next The string in Objective-C programming language is represented using NSString and its subclass NSMutableString provides several ways for creating string objects. The simplest way to create a string object is to use the Objective-C @”…” construct − NSString *greeting = @”Hello”; A simple example for creating and printing a string is shown below. Live Demo #import <Foundation/Foundation.h> int main () { NSString *greeting = @”Hello”; NSLog(@”Greeting message: %@n”, greeting ); return 0; } When the above code is compiled and executed, it produces result something as follows − 2013-09-11 01:21:39.922 demo[23926] Greeting message: Hello Objective-C supports a wide range of methods for manipulate strings − Sr.No. Method & Purpose 1 – (NSString *)capitalizedString; Returns a capitalized representation of the receiver. 2 – (unichar)characterAtIndex:(NSUInteger)index; Returns the character at a given array position. 3 – (double)doubleValue; Returns the floating-point value of the receiver’s text as a double. 4 – (float)floatValue; Returns the floating-point value of the receiver’s text as a float. 5 – (BOOL)hasPrefix:(NSString *)aString; Returns a Boolean value that indicates whether a given string matches the beginning characters of the receiver. 6 – (BOOL)hasSuffix:(NSString *)aString; Returns a Boolean value that indicates whether a given string matches the ending characters of the receiver. 7 – (id)initWithFormat:(NSString *)format …; Returns an NSString object initialized by using a given format string as a template into which the remaining argument values are substituted. 8 – (NSInteger)integerValue; Returns the NSInteger value of the receiver’s text. 9 – (BOOL)isEqualToString:(NSString *)aString; Returns a Boolean value that indicates whether a given string is equal to the receiver using a literal Unicode-based comparison. 10 – (NSUInteger)length; Returns the number of Unicode characters in the receiver. 11 – (NSString *)lowercaseString; Returns lowercased representation of the receiver. 12 – (NSRange)rangeOfString:(NSString *)aString; Finds and returns the range of the first occurrence of a given string within the receiver. 13 – (NSString *)stringByAppendingFormat:(NSString *)format …; Returns a string made by appending to the receiver a string constructed from a given format string and the following arguments. 14 – (NSString *)stringByTrimmingCharactersInSet:(NSCharacterSet *)set; Returns a new string made by removing from both ends of the receiver characters contained in a given character set. 15 – (NSString *)substringFromIndex:(NSUInteger)anIndex; Returns a new string containing the characters of the receiver from the one at a given index to the end. Following example makes use of few of the above-mentioned functions − Live Demo #import <Foundation/Foundation.h> int main () { NSString *str1 = @”Hello”; NSString *str2 = @”World”; NSString *str3; int len ; NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; /* uppercase string */ str3 = [str2 uppercaseString]; NSLog(@”Uppercase String : %@n”, str3 ); /* concatenates str1 and str2 */ str3 = [str1 stringByAppendingFormat:@”World”]; NSLog(@”Concatenated string: %@n”, str3 ); /* total length of str3 after concatenation */ len = [str3 length]; NSLog(@”Length of Str3 : %dn”, len ); /* InitWithFormat */ str3 = [[NSString alloc] initWithFormat:@”%@ %@”,str1,str2]; NSLog(@”Using initWithFormat: %@n”, str3 ); [pool drain]; return 0; } When the above code is compiled and executed, it produces result something as follows − 2013-09-11 01:15:45.069 demo[30378] Uppercase String : WORLD 2013-09-11 01:15:45.070 demo[30378] Concatenated string: HelloWorld 2013-09-11 01:15:45.070 demo[30378] Length of Str3 : 10 2013-09-11 01:15:45.070 demo[30378] Using initWithFormat: Hello World You can find a complete list of Objective-C NSString related methods in NSString Class Reference. Print Page Previous Next Advertisements ”;

Objective-C – Operators

Objective-C Operators ”; Previous Next An operator is a symbol that tells the compiler to perform specific mathematical or logical manipulations. Objective-C language is rich in built-in operators and provides following types of operators − Arithmetic Operators Relational Operators Logical Operators Bitwise Operators Assignment Operators Misc Operators This tutorial will explain the arithmetic, relational, logical, bitwise, assignment and other operators one by one. Arithmetic Operators Following table shows all the arithmetic operators supported by Objective-C language. Assume variable A holds 10 and variable B holds 20, then − Show Examples Operator Description Example + Adds two operands A + B will give 30 – Subtracts second operand from the first A – B will give -10 * Multiplies both operands A * B will give 200 / Divides numerator by denominator B / A will give 2 % Modulus Operator and remainder of after an integer division B % A will give 0 ++ Increment operator increases integer value by one A++ will give 11 — Decrement operator decreases integer value by one A– will give 9 Relational Operators Following table shows all the relational operators supported by Objective-C language. Assume variable A holds 10 and variable B holds 20, then − Show Examples Operator Description Example == Checks if the values of two operands are equal or not; if yes, then condition becomes true. (A == B) is not true. != Checks if the values of two operands are equal or not; if values are not equal, then condition becomes true. (A != B) is true. > Checks if the value of left operand is greater than the value of right operand; if yes, then condition becomes true. (A > B) is not true. < Checks if the value of left operand is less than the value of right operand; if yes, then condition becomes true. (A < B) is true. >= Checks if the value of left operand is greater than or equal to the value of right operand; if yes, then condition becomes true. (A >= B) is not true. <= Checks if the value of left operand is less than or equal to the value of right operand; if yes, then condition becomes true. (A <= B) is true. Logical Operators Following table shows all the logical operators supported by Objective-C language. Assume variable A holds 1 and variable B holds 0, then − Show Examples Operator Description Example && Called Logical AND operator. If both the operands are non zero then condition becomes true. (A && B) is false. || Called Logical OR Operator. If any of the two operands is non zero then condition becomes true. (A || B) is true. ! Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true, then Logical NOT operator will make false. !(A && B) is true. Bitwise Operators Bitwise operator works on bits and perform bit by bit operation. The truth tables for &, |, and ^ are as follows − p q p & q p | q p ^ q 0 0 0 0 0 0 1 0 1 1 1 1 1 1 0 1 0 0 1 1 Assume if A = 60; and B = 13; now in binary format they will be as follows − A = 0011 1100 B = 0000 1101 —————– A&B = 0000 1100 A|B = 0011 1101 A^B = 0011 0001 ~A  = 1100 0011 The Bitwise operators supported by Objective-C language are listed in the following table. Assume variable A holds 60 and variable B holds 13 then − Show Examples Operator Description Example & Binary AND Operator copies a bit to the result if it exists in both operands. (A & B) will give 12, which is 0000 1100 | Binary OR Operator copies a bit if it exists in either operand. (A | B) will give 61, which is 0011 1101 ^ Binary XOR Operator copies the bit if it is set in one operand but not both. (A ^ B) will give 49, which is 0011 0001 ~ Binary Ones Complement Operator is unary and has the effect of ”flipping” bits. (~A ) will give -61, which is 1100 0011 in 2”s complement form. << Binary Left Shift Operator. The left operands value is moved left by the number of bits specified by the right operand. A << 2 will give 240, which is 1111 0000 >> Binary Right Shift Operator. The left operands value is moved right by the number of bits specified by the right operand. A >> 2 will give 15, which is 0000 1111 Assignment Operators There are following assignment operators supported by Objective-C language − Show Examples Operator Description Example = Simple assignment operator, Assigns values from right side operands to left side operand C = A + B will assign value of A + B into C += Add AND assignment operator, It adds right operand to the left operand and assigns the result to left operand C += A is equivalent to C = C + A -= Subtract AND assignment operator, It subtracts right operand from the left operand and assigns the result to left operand C -= A is equivalent to C = C – A *= Multiply AND assignment operator, It multiplies right operand with the left operand and assigns the result to left operand C *= A is equivalent to C = C * A /= Divide AND assignment operator, It divides left operand with the right operand and assigns the result to left operand C /= A is equivalent to C = C / A %= Modulus AND assignment operator, It takes modulus using two operands and assigns the result to left operand C %= A is equivalent to C = C % A <<= Left shift AND assignment operator C <<= 2 is same as C = C << 2 >>= Right shift AND assignment operator