Objective-C Program Structure ”; Previous Next 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 Demo #import <Foundation/Foundation.h> @interface SampleClass:NSObject – (void)sampleMethod; @end @implementation SampleClass – (void)sampleMethod { NSLog(@”Hello, World! n”); } @end int main() { /* my first program in Objective-C */ SampleClass *sampleClass = [[SampleClass alloc]init]; [sampleClass sampleMethod]; return 0; } Let us look various parts of the above program − The first line of the program #import <Foundation/Foundation.h> is a preprocessor command, which tells a Objective-C compiler to include Foundation.h file before going to actual compilation. The next line @interface SampleClass:NSObject shows how to create an interface. It inherits NSObject, which is the base class of all objects. The next line – (void)sampleMethod; shows how to declare a method. The next line @end marks the end of an interface. The next line @implementation SampleClass shows how to implement the interface SampleClass. The next line – (void)sampleMethod{} shows the implementation of the sampleMethod. The next line @end marks the end of an implementation. The next line int main() is the main function where program execution begins. The next line /*…*/ will be ignored by the compiler and it has been put to add additional comments in the program. So such lines are called comments in the program. The next line NSLog(…) is another function available in Objective-C which causes the message “Hello, World!” to be displayed on the screen. The next line return 0; terminates main()function and returns the value 0. Compile & Execute Objective-C Program Now when we compile and run the program, we will get the following result. 2017-10-06 07:48:32.020 demo[65832] Hello, World! Print Page Previous Next Advertisements ”;
Category: objective C
Objective-C Environment Setup ”; Previous Next Local Environment Setup If you are still willing to set up your own environment for Objective-C programming language, then you need to install Text Editor and The GCC Compiler on your computer. 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 Print Page Previous Next Advertisements ”;
Objective-C Composite Objects ”; Previous Next We can create subclass within a class cluster that defines a class that embeds within it an object. These class objects are composite objects. So you might be wondering what”s a class cluster. So we will first see what”s a class cluster. Class Clusters Class clusters are a design pattern that the foundation framework makes extensive use of. Class clusters group a number of private concrete subclasses under a public abstract superclass. The grouping of classes in this way simplifies the publicly visible architecture of an object-oriented framework without reducing its functional richness. Class clusters are based on the abstract factory design pattern. To make it simple, instead of creating multiple classes for similar functions, we create a single class that will take care of its handling based on the value of input. For example, in NSNumber we have many clusters of classes like char, int, bool and so on. We group all of them to a single class that takes care of handling the similar operations in a single class. NSNumber actually wraps the value of these primitive types into objects. What is a Composite Object? By embedding a private cluster object in an object of our own design, we create a composite object. This composite object can rely on the cluster object for its basic functionality, only intercepting messages that the composite object wants to handle in some particular way. This architecture reduces the amount of code we must write and lets you take advantage of the tested code provided by the Foundation Framework. This is explained in the following figure. The composite object must declare itself to be a subclass of the cluster”s abstract superclass. As a subclass, it must override the superclass” primitive methods. It can also override derived methods, but this isn”t necessary because the derived methods work through the primitive ones. The count method of the NSArray class is an example; the intervening object”s implementation of a method it overrides can be as simple as − – (unsigned)count { return [embeddedObject count]; } In the above example, embedded object is actually of type NSArray. A Composite Object Example Now in order to see a complete example, let”s look at the example from the Apple documentation which is given below. Live Demo #import <Foundation/Foundation.h> @interface ValidatingArray : NSMutableArray { NSMutableArray *embeddedArray; } + validatingArray; – init; – (unsigned)count; – objectAtIndex:(unsigned)index; – (void)addObject:object; – (void)replaceObjectAtIndex:(unsigned)index withObject:object; – (void)removeLastObject; – (void)insertObject:object atIndex:(unsigned)index; – (void)removeObjectAtIndex:(unsigned)index; @end @implementation ValidatingArray – init { self = [super init]; if (self) { embeddedArray = [[NSMutableArray allocWithZone:[self zone]] init]; } return self; } + validatingArray { return [[self alloc] init] ; } – (unsigned)count { return [embeddedArray count]; } – objectAtIndex:(unsigned)index { return [embeddedArray objectAtIndex:index]; } – (void)addObject:(id)object { if (object != nil) { [embeddedArray addObject:object]; } } – (void)replaceObjectAtIndex:(unsigned)index withObject:(id)object; { if (index <[embeddedArray count] && object != nil) { [embeddedArray replaceObjectAtIndex:index withObject:object]; } } – (void)removeLastObject; { if ([embeddedArray count] > 0) { [embeddedArray removeLastObject]; } } – (void)insertObject:(id)object atIndex:(unsigned)index; { if (object != nil) { [embeddedArray insertObject:object atIndex:index]; } } – (void)removeObjectAtIndex:(unsigned)index; { if (index <[embeddedArray count]) { [embeddedArray removeObjectAtIndex:index]; } } @end int main() { NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; ValidatingArray *validatingArray = [ValidatingArray validatingArray]; [validatingArray addObject:@”Object1″]; [validatingArray addObject:@”Object2″]; [validatingArray addObject:[NSNull null]]; [validatingArray removeObjectAtIndex:2]; NSString *aString = [validatingArray objectAtIndex:1]; NSLog(@”The value at Index 1 is %@”,aString); [pool drain]; return 0; } Now when we compile and run the program, we will get the following result. 2013-09-28 22:03:54.294 demo[6247] The value at Index 1 is Object2 In the above example, we can see that validating array”s one function would not allow adding null objects that will lead to crash in the normal scenario. But our validating array takes care of it. Similarly, each of the method in validating array adds validating processes apart from the normal sequence of operations. Print Page Previous Next Advertisements ”;
Obj-C – Foundation Framework
Obj-C Foundation Framework ”; Previous Next If you refer Apple documentation, you can see the details of Foundation framework as given below. The Foundation framework defines a base layer of Objective-C classes. In addition to providing a set of useful primitive object classes, it introduces several paradigms that define functionality not covered by the Objective-C language. The Foundation framework is designed with these goals in mind − Provide a small set of basic utility classes. Make software development easier by introducing consistent conventions for things such as de-allocation. Support Unicode strings, object persistence, and object distribution. Provide a level of OS independence to enhance portability. The framework was developed by NeXTStep, which was acquired by Apple and these foundation classes became part of Mac OS X and iOS. As it was developed by NeXTStep, it has class prefix of “NS”. We have used Foundation Framework in all our sample programs. It is almost a must to use Foundation Framework. Generally, we use something like #import <Foundation/NSString.h> to import a Objective-C class, but in order avoid importing too many classes, it”s all imported in #import <Foundation/Foundation.h>. NSObject is the base class of all objects including the foundation kit classes. It provides the methods for memory management. It also provides basic interface to the runtime system and ability to behave as Objective-C objects. It doesn”t have any base class and is the root for all classes. Foundation Classes based on functionality Sr.No. Loop Type & Description 1 Data storage NSArray, NSDictionary, and NSSet provide storage for Objective-C objects of any class. 2 Text and strings NSCharacterSet represents various groupings of characters that are used by the NSString and NSScanner classes. The NSString classes represent text strings and provide methods for searching, combining, and comparing strings. An NSScanner object is used to scan numbers and words from an NSString object. 3 Dates and times The NSDate, NSTimeZone, and NSCalendar classes store times and dates and represent calendrical information. They offer methods for calculating date and time differences. Together with NSLocale, they provide methods for displaying dates and times in many formats and for adjusting times and dates based on location in the world. 4 Exception handling Exception handling is used to handle unexpected situations and it”s offered in Objective-C with NSException. 5 File handling File handling is done with the help of class NSFileManager. 6 URL loading system A set of classes and protocols that provide access to common Internet protocols. Print Page Previous Next Advertisements ”;
Objective-C – Discussion
Discuss Objective-C ”; Previous Next Objective-C is a general-purpose, object-oriented programming language that adds Smalltalk-style messaging to the C programming language. This is the main programming language used by Apple for the OS X and iOS operating systems and their respective APIs, Cocoa and Cocoa Touch. This reference will take you through simple and practical approach while learning Objective-C Programming language. Print Page Previous Next Advertisements ”;
Objective-C – Data Types
Objective-C Data Types ”; Previous Next In the Objective-C programming language, data types refer to an extensive system used for declaring variables or functions of different types. The type of a variable determines how much space it occupies in storage and how the bit pattern stored is interpreted. The types in Objective-C can be classified as follows − Sr.No. Types & Description 1 Basic Types − They are arithmetic types and consist of the two types: (a) integer types and (b) floating-point types. 2 Enumerated types − They are again arithmetic types and they are used to define variables that can only be assigned certain discrete integer values throughout the program. 3 The type void − The type specifier void indicates that no value is available. 4 Derived types − They include (a) Pointer types, (b) Array types, (c) Structure types, (d) Union types and (e) Function types. The array types and structure types are referred to collectively as the aggregate types. The type of a function specifies the type of the function”s return value. We will see basic types in the following section whereas other types will be covered in the upcoming chapters. Integer Types Following table gives you details about standard integer types with its storage sizes and value ranges − Type Storage size Value range char 1 byte -128 to 127 or 0 to 255 unsigned char 1 byte 0 to 255 signed char 1 byte -128 to 127 int 2 or 4 bytes -32,768 to 32,767 or -2,147,483,648 to 2,147,483,647 unsigned int 2 or 4 bytes 0 to 65,535 or 0 to 4,294,967,295 short 2 bytes -32,768 to 32,767 unsigned short 2 bytes 0 to 65,535 long 4 bytes -2,147,483,648 to 2,147,483,647 unsigned long 4 bytes 0 to 4,294,967,295 To get the exact size of a type or a variable on a particular platform, you can use the sizeof operator. The expression sizeof(type) yields the storage size of the object or type in bytes. Following is an example to get the size of int type on any machine − Live Demo #import <Foundation/Foundation.h> int main() { NSLog(@”Storage size for int : %d n”, sizeof(int)); return 0; } When you compile and execute the above program, it produces the following result on Linux − 2013-09-07 22:21:39.155 demo[1340] Storage size for int : 4 Floating-Point Types Following table gives you details about standard float-point types with storage sizes and value ranges and their precision − Type Storage size Value range Precision float 4 byte 1.2E-38 to 3.4E+38 6 decimal places double 8 byte 2.3E-308 to 1.7E+308 15 decimal places long double 10 byte 3.4E-4932 to 1.1E+4932 19 decimal places The header file float.h defines macros that allow you to use these values and other details about the binary representation of real numbers in your programs. Following example will print storage space taken by a float type and its range values − Live Demo #import <Foundation/Foundation.h> int main() { NSLog(@”Storage size for float : %d n”, sizeof(float)); return 0; } When you compile and execute the above program, it produces the following result on Linux − 2013-09-07 22:22:21.729 demo[3927] Storage size for float : 4 The void Type The void type specifies that no value is available. It is used in three kinds of situations − Sr.No. Types and Description 1 Function returns as void There are various functions in Objective-C which do not return value or you can say they return void. A function with no return value has the return type as void. For example, void exit (int status); 2 Function arguments as void There are various functions in Objective-C which do not accept any parameter. A function with no parameter can accept as a void. For example, int rand(void); The void type may not be understood to you at this point, so let us proceed and we will cover these concepts in upcoming chapters. Print Page Previous Next Advertisements ”;
Objective-C – Arrays
Objective-C Arrays ”; Previous Next Objective-C programming language provides a data structure called the array, which can store a fixed-size sequential collection of elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type. Instead of declaring individual variables, such as number0, number1, …, and number99, you declare one array variable such as numbers and use numbers[0], numbers[1], and …, numbers[99] to represent individual variables. A specific element in an array is accessed by an index. All arrays consist of contiguous memory locations. The lowest address corresponds to the first element and the highest address to the last element. Declaring Arrays To declare an array in Objective-C, a programmer specifies the type of the elements and the number of elements required by an array as follows − type arrayName [ arraySize ]; This is called a single-dimensional array. The arraySize must be an integer constant greater than zero and type can be any valid Objective-C data type. For example, to declare a 10-element array called balance of type double, use this statement − double balance[10]; Now, balance is a variable array, which is sufficient to hold up to 10 double numbers. Initializing Arrays You can initialize an array in Objective-C either one by one or using a single statement as follows − double balance[5] = {1000.0, 2.0, 3.4, 17.0, 50.0}; The number of values between braces { } can not be larger than the number of elements that we declare for the array between square brackets [ ]. Following is an example to assign a single element of the array − If you omit the size of the array, an array just big enough to hold the initialization is created. Therefore, if you write − double balance[] = {1000.0, 2.0, 3.4, 17.0, 50.0}; You will create exactly the same array as you did in the previous example. balance[4] = 50.0; The above statement assigns element number 5th in the array a value of 50.0. Array with 4th index will be 5th, i.e., last element because all arrays have 0 as the index of their first element which is also called base index. Following is the pictorial representation of the same array we discussed above − Accessing Array Elements An element is accessed by indexing the array name. This is done by placing the index of the element within square brackets after the name of the array. For example − double salary = balance[9]; The above statement will take 10th element from the array and assign the value to salary variable. Following is an example, which will use all the above mentioned three concepts viz. declaration, assignment and accessing arrays − Live Demo #import <Foundation/Foundation.h> int main () { int n[ 10 ]; /* n is an array of 10 integers */ int i,j; /* initialize elements of array n to 0 */ for ( i = 0; i < 10; i++ ) { n[ i ] = i + 100; /* set element at location i to i + 100 */ } /* output each array element”s value */ for (j = 0; j < 10; j++ ) { NSLog(@”Element[%d] = %dn”, j, n[j] ); } return 0; } When the above code is compiled and executed, it produces the following result − 2013-09-14 01:24:06.669 demo[16508] Element[0] = 100 2013-09-14 01:24:06.669 demo[16508] Element[1] = 101 2013-09-14 01:24:06.669 demo[16508] Element[2] = 102 2013-09-14 01:24:06.669 demo[16508] Element[3] = 103 2013-09-14 01:24:06.669 demo[16508] Element[4] = 104 2013-09-14 01:24:06.669 demo[16508] Element[5] = 105 2013-09-14 01:24:06.669 demo[16508] Element[6] = 106 2013-09-14 01:24:06.669 demo[16508] Element[7] = 107 2013-09-14 01:24:06.669 demo[16508] Element[8] = 108 2013-09-14 01:24:06.669 demo[16508] Element[9] = 109 Objective-C Arrays in Detail Arrays are important to Objective-C and need lots of more details. There are following few important concepts related to array which should be clear to a Objective-C programmer − Sr.No. Concept & Description 1 Multi-dimensional arrays Objective-C supports multidimensional arrays. The simplest form of the multidimensional array is the two-dimensional array. 2 Passing arrays to functions You can pass to the function a pointer to an array by specifying the array”s name without an index. 3 Return array from a function Objective-C allows a function to return an array. 4 Pointer to an array You can generate a pointer to the first element of an array by simply specifying the array name, without any index. Print Page Previous Next Advertisements ”;
Objective-C – Type Casting
Objective-C Type Casting ”; Previous Next Type casting is a way to convert a variable from one data type to another data type. For example, if you want to store a long value into a simple integer then you can type cast long to int. You can convert values from one type to another explicitly using the cast operator as follows − (type_name) expression In Objective-C, we generally use CGFloat for doing floating point operation, which is derived from basic type of float in case of 32-bit and double in case of 64-bit. Consider the following example where the cast operator causes the division of one integer variable by another to be performed as a floating-point operation − Live Demo #import <Foundation/Foundation.h> int main() { int sum = 17, count = 5; CGFloat mean; mean = (CGFloat) sum / count; NSLog(@”Value of mean : %fn”, mean ); return 0; } When the above code is compiled and executed, it produces the following result − 2013-09-11 01:35:40.047 demo[20634] Value of mean : 3.400000 It should be noted here that the cast operator has precedence over division, so the value of sum is first converted to type double and finally it gets divided by count yielding a double value. Type conversions can be implicit which is performed by the compiler automatically or it can be specified explicitly through the use of the cast operator. It is considered good programming practice to use the cast operator whenever type conversions are necessary. Integer Promotion Integer promotion is the process by which values of integer type “smaller” than int or unsigned int are converted either to int or unsigned int. Consider an example of adding a character in an int − Live Demo #import <Foundation/Foundation.h> int main() { int i = 17; char c = ”c”; /* ascii value is 99 */ int sum; sum = i + c; NSLog(@”Value of sum : %dn”, sum ); return 0; } When the above code is compiled and executed, it produces the following result − 2013-09-11 01:38:28.492 demo[980] Value of sum : 116 Here, value of sum is coming as 116 because compiler is doing integer promotion and converting the value of ”c” to ascii before performing actual addition operation. Usual Arithmetic Conversion The usual arithmetic conversions are implicitly performed to cast their values in a common type. Compiler first performs integer promotion, if operands still have different types then they are converted to the type that appears highest in the following hierarchy − The usual arithmetic conversions are not performed for the assignment operators, nor for the logical operators && and ||. Let us take following example to understand the concept − Live Demo #import <Foundation/Foundation.h> int main() { int i = 17; char c = ”c”; /* ascii value is 99 */ CGFloat sum; sum = i + c; NSLog(@”Value of sum : %fn”, sum ); return 0; } When the above code is compiled and executed, it produces the following result − 2013-09-11 01:41:39.192 demo[15351] Value of sum : 116.000000 Here, it is simple to understand that first c gets converted to integer but because final value is float, so usual arithmetic conversion applies and compiler converts i and c into float and add them yielding a float result. Print Page Previous Next Advertisements ”;
Objective-C – Typedef
Objective-C Typedef ”; Previous Next The Objective-C programming language provides a keyword called typedef, which you can use to give a type a new name. Following is an example to define a term BYTE for one-byte numbers − typedef unsigned char BYTE; After this type definition, the identifier BYTE can be used as an abbreviation for the type unsigned char, for example:. BYTE b1, b2; By convention, uppercase letters are used for these definitions to remind the user that the type name is really a symbolic abbreviation, but you can use lowercase, as follows − typedef unsigned char byte; You can use typedef to give a name to user-defined data type as well. For example, you can use typedef with structure to define a new data type and then use that data type to define structure variables directly as follows − Live Demo #import <Foundation/Foundation.h> typedef struct Books { NSString *title; NSString *author; NSString *subject; int book_id; } Book; int main() { Book book; book.title = @”Objective-C Programming”; book.author = @”TutorialsPoint”; book.subject = @”Programming tutorial”; book.book_id = 100; NSLog( @”Book title : %@n”, book.title); NSLog( @”Book author : %@n”, book.author); NSLog( @”Book subject : %@n”, book.subject); NSLog( @”Book Id : %dn”, book.book_id); return 0; } When the above code is compiled and executed, it produces the following result − 2013-09-12 12:21:53.745 demo[31183] Book title : Objective-C Programming 2013-09-12 12:21:53.745 demo[31183] Book author : TutorialsPoint 2013-09-12 12:21:53.745 demo[31183] Book subject : Programming tutorial 2013-09-12 12:21:53.745 demo[31183] Book Id : 100 typedef vs #define The #define is a Objective-C directive, which is also used to define the aliases for various data types similar to typedef but with following differences − The typedef is limited to giving symbolic names to types only whereas #define can be used to define alias for values as well, like you can define 1 as ONE, etc. The typedef interpretation is performed by the compiler where as #define statements are processed by the pre-processor. Following is a simplest usage of #define − Live Demo #import <Foundation/Foundation.h> #define TRUE 1 #define FALSE 0 int main( ) { NSLog( @”Value of TRUE : %dn”, TRUE); NSLog( @”Value of FALSE : %dn”, FALSE); return 0; } When the above code is compiled and executed, it produces the following result − 2013-09-12 12:23:37.993 demo[5160] Value of TRUE : 1 2013-09-12 12:23:37.994 demo[5160] Value of FALSE : 0 Print Page Previous Next Advertisements ”;
Objective-C Classes & Objects ”; Previous Next The main purpose of Objective-C programming language is to add object orientation to the C programming language and classes are the central feature of Objective-C that support object-oriented programming and are often called user-defined types. A class is used to specify the form of an object and it combines data representation and methods for manipulating that data into one neat package. The data and methods within a class are called members of the class. Objective-C Characteristic The class is defined in two different sections namely @interface and @implementation. Almost everything is in form of objects. Objects receive messages and objects are often referred as receivers. Objects contain instance variables. Objects and instance variables have scope. Classes hide an object”s implementation. Properties are used to provide access to class instance variables in other classes. Objective-C Class Definitions When you define a class, you define a blueprint for a data type. This doesn”t actually define any data, but it does define what the class name means, that is, what an object of the class will consist of and what operations can be performed on such an object. A class definition starts with the keyword @interface followed by the interface(class) name; and the class body, enclosed by a pair of curly braces. In Objective-C, all classes are derived from the base class called NSObject. It is the superclass of all Objective-C classes. It provides basic methods like memory allocation and initialization. For example, we defined the Box data type using the keyword class as follows − @interface Box:NSObject { //Instance variables double length; // Length of a box double breadth; // Breadth of a box } @property(nonatomic, readwrite) double height; // Property @end The instance variables are private and are only accessible inside the class implementation. Allocating and Initializing Objective-C Objects A class provides the blueprints for objects, so basically an object is created from a class. We declare objects of a class with exactly the same sort of declaration that we declare variables of basic types. Following statements declare two objects of class Box − Box box1 = [[Box alloc]init]; // Create box1 object of type Box Box box2 = [[Box alloc]init]; // Create box2 object of type Box Both of the objects box1 and box2 will have their own copy of data members. Accessing the Data Members The properties of objects of a class can be accessed using the direct member access operator (.). Let us try the following example to make things clear − Live Demo #import <Foundation/Foundation.h> @interface Box:NSObject { double length; // Length of a box double breadth; // Breadth of a box double height; // Height of a box } @property(nonatomic, readwrite) double height; // Property -(double) volume; @end @implementation Box @synthesize height; -(id)init { self = [super init]; length = 1.0; breadth = 1.0; return self; } -(double) volume { return length*breadth*height; } @end int main() { NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; Box *box1 = [[Box alloc]init]; // Create box1 object of type Box Box *box2 = [[Box alloc]init]; // Create box2 object of type Box double volume = 0.0; // Store the volume of a box here // box 1 specification box1.height = 5.0; // box 2 specification box2.height = 10.0; // volume of box 1 volume = [box1 volume]; NSLog(@”Volume of Box1 : %f”, volume); // volume of box 2 volume = [box2 volume]; NSLog(@”Volume of Box2 : %f”, volume); [pool drain]; return 0; } When the above code is compiled and executed, it produces the following result − 2013-09-22 21:25:33.314 ClassAndObjects[387:303] Volume of Box1 : 5.000000 2013-09-22 21:25:33.316 ClassAndObjects[387:303] Volume of Box2 : 10.000000 Properties Properties are introduced in Objective-C to ensure that the instance variable of the class can be accessed outside the class. The various parts are the property declaration are as follows. Properties begin with @property, which is a keyword It is followed with access specifiers, which are nonatomic or atomic, readwrite or readonly and strong, unsafe_unretained or weak. This varies based on the type of the variable. For any pointer type, we can use strong, unsafe_unretained or weak. Similarly for other types we can use readwrite or readonly. This is followed by the datatype of the variable. Finally, we have the property name terminated by a semicolon. We can add synthesize statement in the implementation class. But in the latest XCode, the synthesis part is taken care by the XCode and you need not include synthesize statement. It is only possible with the properties we can access the instance variables of the class. Actually, internally getter and setter methods are created for the properties. For example, let”s assume we have a property @property (nonatomic ,readonly ) BOOL isDone. Under the hood, there are setters and getters created as shown below. -(void)setIsDone(BOOL)isDone; -(BOOL)isDone; Print Page Previous Next Advertisements ”;