Objective-C Protocols ”; Previous Next Objective-C allows you to define protocols, which declare the methods expected to be used for a particular situation. Protocols are implemented in the classes conforming to the protocol. A simple example would be a network URL handling class, it will have a protocol with methods like processCompleted delegate method that intimates the calling class once the network URL fetching operation is over. A syntax of protocol is shown below. @protocol ProtocolName @required // list of required methods @optional // list of optional methods @end The methods under keyword @required must be implemented in the classes that conforms to the protocol and the methods under @optional keyword are optional to implement. Here is the syntax for class conforming to protocol @interface MyClass : NSObject <MyProtocol> … @end This means that any instance of MyClass will respond not only to the methods declared specifically in the interface, but that MyClass also provides implementations for the required methods in MyProtocol. There”s no need to redeclare the protocol methods in the class interface – the adoption of the protocol is sufficient. If you need a class to adopt multiple protocols, you can specify them as a comma-separated list. We have a delegate object that holds the reference of the calling object that implements the protocol. An example is shown below. Live Demo #import <Foundation/Foundation.h> @protocol PrintProtocolDelegate – (void)processCompleted; @end @interface PrintClass :NSObject { id delegate; } – (void) printDetails; – (void) setDelegate:(id)newDelegate; @end @implementation PrintClass – (void)printDetails { NSLog(@”Printing Details”); [delegate processCompleted]; } – (void) setDelegate:(id)newDelegate { delegate = newDelegate; } @end @interface SampleClass:NSObject<PrintProtocolDelegate> – (void)startAction; @end @implementation SampleClass – (void)startAction { PrintClass *printClass = [[PrintClass alloc]init]; [printClass setDelegate:self]; [printClass printDetails]; } -(void)processCompleted { NSLog(@”Printing Process Completed”); } @end int main(int argc, const char * argv[]) { NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; SampleClass *sampleClass = [[SampleClass alloc]init]; [sampleClass startAction]; [pool drain]; return 0; } Now when we compile and run the program, we will get the following result. 2013-09-22 21:15:50.362 Protocols[275:303] Printing Details 2013-09-22 21:15:50.364 Protocols[275:303] Printing Process Completed In the above example we have seen how the delgate methods are called and executed. Its starts with startAction, once the process is completed, the delegate method processCompleted is called to intimate the operation is completed. In any iOS or Mac app, we will never have a program implemented without a delegate. So its important we understand the usage of delegates. Delegates objects should use unsafe_unretained property type to avoid memory leaks. Print Page Previous Next Advertisements ”;
Category: Computer Programming
Objective-C Dynamic Binding ”; Previous Next Dynamic binding is determining the method to invoke at runtime instead of at compile time. Dynamic binding is also referred to as late binding. In Objective-C, all methods are resolved dynamically at runtime. The exact code executed is determined by both the method name (the selector) and the receiving object. Dynamic binding enables polymorphism. For example, consider a collection of objects including Rectangle and Square. Each object has its own implementation of a printArea method. In the following code fragment, the actual code that should be executed by the expression [anObject printArea] is determined at runtime. The runtime system uses the selector for the method run to identify the appropriate method in whatever class of anObject turns out to be. Let us look at a simple code that would explain dynamic binding. Live Demo #import <Foundation/Foundation.h> @interface Square:NSObject { float area; } – (void)calculateAreaOfSide:(CGFloat)side; – (void)printArea; @end @implementation Square – (void)calculateAreaOfSide:(CGFloat)side { area = side * side; } – (void)printArea { NSLog(@”The area of square is %f”,area); } @end @interface Rectangle:NSObject { float area; } – (void)calculateAreaOfLength:(CGFloat)length andBreadth:(CGFloat)breadth; – (void)printArea; @end @implementation Rectangle – (void)calculateAreaOfLength:(CGFloat)length andBreadth:(CGFloat)breadth { area = length * breadth; } – (void)printArea { NSLog(@”The area of Rectangle is %f”,area); } @end int main() { Square *square = [[Square alloc]init]; [square calculateAreaOfSide:10.0]; Rectangle *rectangle = [[Rectangle alloc]init]; [rectangle calculateAreaOfLength:10.0 andBreadth:5.0]; NSArray *shapes = [[NSArray alloc]initWithObjects: square, rectangle,nil]; id object1 = [shapes objectAtIndex:0]; [object1 printArea]; id object2 = [shapes objectAtIndex:1]; [object2 printArea]; return 0; } Now when we compile and run the program, we will get the following result. 2013-09-28 07:42:29.821 demo[4916] The area of square is 100.000000 2013-09-28 07:42:29.821 demo[4916] The area of Rectangle is 50.000000 As you can see in the above example, printArea method is dynamically selected in runtime. It is an example for dynamic binding and is quite useful in many situations when dealing with similar kind of objects. Print Page Previous Next Advertisements ”;
Objective-C Fast Enumeration ”; Previous Next Fast enumeration is an Objective-C”s feature that helps in enumerating through a collection. So in order to know about fast enumeration, we need know about collection first which will be explained in the following section. Collections in Objective-C Collections are fundamental constructs. It is used to hold and manage other objects. The whole purpose of a collection is that it provides a common way to store and retrieve objects efficiently. There are several different types of collections. While they all fulfill the same purpose of being able to hold other objects, they differ mostly in the way objects are retrieved. The most common collections used in Objective-C are − NSSet NSArray NSDictionary NSMutableSet NSMutableArray NSMutableDictionary If you want to know more about these structures, please refer data storage in Foundation Framework. Fast enumeration Syntax for (classType variable in collectionObject ) { statements } Here is an example for fast enumeration. Live Demo #import <Foundation/Foundation.h> int main() { NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; NSArray *array = [[NSArray alloc] initWithObjects:@”string1″, @”string2″,@”string3″,nil]; for(NSString *aString in array) { NSLog(@”Value: %@”,aString); } [pool drain]; return 0; } Now when we compile and run the program, we will get the following result. 2013-09-28 06:26:22.835 demo[7426] Value: string1 2013-09-28 06:26:22.836 demo[7426] Value: string2 2013-09-28 06:26:22.836 demo[7426] Value: string3 As you can see in the output, each of the objects in the array is printed in an order. Fast Enumeration Backwards for (classType variable in [collectionObject reverseObjectEnumerator] ) { statements } Here is an example for reverseObjectEnumerator in fast enumeration. Live Demo #import <Foundation/Foundation.h> int main() { NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; NSArray *array = [[NSArray alloc] initWithObjects:@”string1″, @”string2″,@”string3″,nil]; for(NSString *aString in [array reverseObjectEnumerator]) { NSLog(@”Value: %@”,aString); } [pool drain]; return 0; } Now when we compile and run the program, we will get the following result. 2013-09-28 06:27:51.025 demo[12742] Value: string3 2013-09-28 06:27:51.025 demo[12742] Value: string2 2013-09-28 06:27:51.025 demo[12742] Value: string1 As you can see in the output, each of the objects in the array is printed but in the reverse order as compared to normal fast enumeration. Print Page Previous Next Advertisements ”;
Command-Line Arguments
Command-Line Arguments ”; Previous Next It is possible to pass some values from the command line to your Objective-C programs when they are executed. These values are called command line arguments and many times they are important for your program, especially when you want to control your program from outside instead of hard coding those values inside the code. The command line arguments are handled using main() function arguments where argc refers to the number of arguments passed, and argv[] is a pointer array, which points to each argument passed to the program. Following is a simple example, which checks if there is any argument supplied from the command line and take action accordingly − Live Demo #import <Foundation/Foundation.h> int main( int argc, char *argv[] ) { if( argc == 2 ) { NSLog(@”The argument supplied is %sn”, argv[1]); } else if( argc > 2 ) { NSLog(@”Too many arguments supplied.n”); } else { NSLog(@”One argument expected.n”); } } When the above code is compiled and executed with a single argument, say “testing”, it produces the following result. 2013-09-13 03:01:17.333 demo[7640] The argument supplied is testing When the above code is compiled and executed with two arguments, say testing1 and testing2, it produces the following result. 2013-09-13 03:01:18.333 demo[7640] Too many arguments supplied. When the above code is compiled and executed without passing any argument, it produces the following result. 2013-09-13 03:01:18.333 demo[7640] One argument expected It should be noted that argv[0] holds the name of the program itself and argv[1] is a pointer to the first command-line argument supplied, and *argv[n] is the last argument. If no arguments are supplied, argc will be one, otherwise if you pass one argument, then argc is set at 2. You pass all the command line arguments separated by a space, but if argument itself has a space, then you can pass such arguments by putting them inside double quotes “” or single quotes ””. Let us re-write above example once again where we will print program name and we also pass a command-line argument by putting inside double quotes − Live Demo #import <Foundation/Foundation.h> int main( int argc, char *argv[] ) { NSLog(@”Program name %sn”, argv[0]); if( argc == 2 ) { NSLog(@”The argument supplied is %sn”, argv[1]); } else if( argc > 2 ) { NSLog(@”Too many arguments supplied.n”); } else { NSLog(@”One argument expected.n”); } return 0; } When the above code is compiled and executed with a single argument separated by space but inside double quotes say “Testing1 Testing2”, it produces the following result. 2017-11-30 06:36:59.081 main[71010] Program name main 2017-11-30 06:36:59.082 main[71010] One argument expected. Print Page Previous Next Advertisements ”;
Objective-C – Log Handling
Objective-C Log Handling ”; Previous Next NSLog method In order to print logs, we use the NSLog method in Objective-C programming language which we have used right from the Hello World example. Let us look at a simple code that would print the words “Hello World” − Live Demo #import <Foundation/Foundation.h> int main() { NSLog(@”Hello, World! n”); return 0; } Now, when we compile and run the program, we will get the following result. 2013-09-16 00:32:50.888 demo[16669] Hello, World! Disabling logs in Live apps Since the NSLogs we use in our application, it will be printed in logs of device and it is not good to print logs in a live build. Hence, we use a type definition for printing logs and we can use them as shown below. Live Demo #import <Foundation/Foundation.h> #if DEBUG == 0 #define DebugLog(…) #elif DEBUG == 1 #define DebugLog(…) NSLog(__VA_ARGS__) #endif int main() { DebugLog(@”Debug log, our custom addition gets printed during debug only” ); NSLog(@”NSLog gets printed always” ); return 0; } Now, when we compile and run the program in debug mode, we will get the following result. 2013-09-11 02:47:07.723 demo[618] Debug log, our custom addition gets printed during debug only 2013-09-11 02:47:07.723 demo[618] NSLog gets printed always Now, when we compile and run the program in release mode, we will get the following result. 2013-09-11 02:47:45.248 demo[3158] NSLog gets printed always Print Page Previous Next Advertisements ”;
Objective-C – Posing
Objective-C Posing ”; Previous Next Before starting about Posing in Objective-C, I would like to bring to your notice that posing was declared deprecated in Mac OS X 10.5 and it”s not available for use thereafter. So for those who are not concerned about these deprecated methods can skip this chapter. Objective-C permits a class to wholly replace another class within a program. The replacing class is said to “pose as” the target class. For the versions that supported posing, all messages sent to the target class are instead received by the posing class. NSObject contains the poseAsClass − method that enables us to replace the existing class as said above. Restrictions in Posing A class may only pose as one of its direct or indirect superclasses. The posing class must not define any new instance variables that are absent from the target class (though it may define or override methods). The target class may not have received any messages prior to the posing. A posing class can call overridden methods through super, thus incorporating the implementation of the target class. A posing class can override methods defined in categories. #import <Foundation/Foundation.h> @interface MyString : NSString @end @implementation MyString – (NSString *)stringByReplacingOccurrencesOfString:(NSString *)target withString:(NSString *)replacement { NSLog(@”The Target string is %@”,target); NSLog(@”The Replacement string is %@”,replacement); } @end int main() { NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; [MyString poseAsClass:[NSString class]]; NSString *string = @”Test”; [string stringByReplacingOccurrencesOfString:@”a” withString:@”c”]; [pool drain]; return 0; } Now when we compile and run the program in a older Mac OS X (V_10.5 or earlier), we will get the following result. 2013-09-22 21:23:46.829 Posing[372:303] The Target string is a 2013-09-22 21:23:46.830 Posing[372:303] The Replacement string is c In the above example, we just polluted the original method with our implementation and this will get affected throughout all the NSString operations with the above method. Print Page Previous Next Advertisements ”;
Objective-C – Extensions
Objective-C Extensions ”; Previous Next A class extension bears some similarity to a category, but it can only be added to a class for which you have the source code at compile time (the class is compiled at the same time as the class extension). The methods declared by a class extension are implemented in the implementation block for the original class, so you can”t, for example, declare a class extension on a framework class, such as a Cocoa or Cocoa Touch class like NSString. Extensions are actually categories without the category name. It”s often referred as anonymous categories. The syntax to declare a extension uses the @interface keyword, just like a standard Objective-C class description, but does not indicate any inheritance from a subclass. Instead, it just adds parentheses, as shown below − @interface ClassName () @end Characteristics of Extensions An extension cannot be declared for any class, only for the classes that we have original implementation of source code. An extension is adding private methods and private variables that are only specific to the class. Any method or variable declared inside the extensions is not accessible even to the inherited classes. Extensions Example Let”s create a class SampleClass that has an extension. In the extension, let”s have a private variable internalID. Then, let”s have a method getExternalID that returns the externalID after processing the internalID. The example is shown below and this wont work on online compiler. #import <Foundation/Foundation.h> @interface SampleClass : NSObject { NSString *name; } – (void)setInternalID; – (NSString *)getExternalID; @end @interface SampleClass() { NSString *internalID; } @end @implementation SampleClass – (void)setInternalID { internalID = [NSString stringWithFormat: @”UNIQUEINTERNALKEY%dUNIQUEINTERNALKEY”,arc4random()%100]; } – (NSString *)getExternalID { return [internalID stringByReplacingOccurrencesOfString: @”UNIQUEINTERNALKEY” withString:@””]; } @end int main(int argc, const char * argv[]) { NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; SampleClass *sampleClass = [[SampleClass alloc]init]; [sampleClass setInternalID]; NSLog(@”ExternalID: %@”,[sampleClass getExternalID]); [pool drain]; return 0; } Now when we compile and run the program, we will get the following result. 2013-09-22 21:18:31.754 Extensions[331:303] ExternalID: 51 In the above example, we can see that the internalID is not returned directly. We here remove the UNIQUEINTERNALKEY and only make the remaining value available to the method getExternalID. The above example just uses a string operation, but it can have many features like encryption/decryption and so on. Print Page Previous Next Advertisements ”;
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 =