Objective-C Preprocessors ”; Previous Next The Objective-C Preprocessor is not part of the compiler, but is a separate step in the compilation process. In simplistic terms, an Objective-C Preprocessor is just a text substitution tool and it instructs compiler to do required pre-processing before actual compilation. We”ll refer to the Objective-C Preprocessor as the OCPP. All preprocessor commands begin with a pound symbol (#). It must be the first nonblank character, and for readability, a preprocessor directive should begin in first column. Following section lists down all important preprocessor directives − Sr.No. Directive & Description 1 #define Substitutes a preprocessor macro 2 #include Inserts a particular header from another file 3 #undef Undefines a preprocessor macro 4 #ifdef Returns true if this macro is defined 5 #ifndef Returns true if this macro is not defined 6 #if Tests if a compile time condition is true 7 #else The alternative for #if 8 #elif #else an #if in one statement 9 #endif Ends preprocessor conditional 10 #error Prints error message on stderr 11 #pragma Issues special commands to the compiler using a standardized method Preprocessors Examples Analyze the following examples to understand various directives. #define MAX_ARRAY_LENGTH 20 This directive tells the OCPP to replace instances of MAX_ARRAY_LENGTH with 20. Use #define for constants to increase readability. #import <Foundation/Foundation.h> #include “myheader.h” These directives tell the OCPP to get foundation.h from Foundation Framework and add the text to the current source file. The next line tells OCPP to get myheader.h from the local directory and add the content to the current source file. #undef FILE_SIZE #define FILE_SIZE 42 This tells the OCPP to undefine existing FILE_SIZE and define it as 42. #ifndef MESSAGE #define MESSAGE “You wish!” #endif This tells the OCPP to define MESSAGE only if MESSAGE isn”t already defined. #ifdef DEBUG /* Your debugging statements here */ #endif This tells the OCPP to do the process the statements enclosed if DEBUG is defined. This is useful if you pass the -DDEBUG flag to gcc compiler at the time of compilation. This will define DEBUG, so you can turn debugging on and off on the fly during compilation. Predefined Macros ANSI C defines a number of macros. Although each one is available for your use in programming, the predefined macros should not be directly modified. Sr.No. Macro & Description 1 __DATE__ The current date as a character literal in “MMM DD YYYY” format 2 __TIME__ The current time as a character literal in “HH:MM:SS” format 3 __FILE__ This contains the current filename as a string literal. 4 __LINE__ This contains the current line number as a decimal constant. 5 __STDC__ Defined as 1 when the compiler complies with the ANSI standard. Let”s try the following example − Live Demo #import <Foundation/Foundation.h> int main() { NSLog(@”File :%sn”, __FILE__ ); NSLog(@”Date :%sn”, __DATE__ ); NSLog(@”Time :%sn”, __TIME__ ); NSLog(@”Line :%dn”, __LINE__ ); NSLog(@”ANSI :%dn”, __STDC__ ); return 0; } When the above code in a file main.m is compiled and executed, it produces the following result − 2013-09-14 04:46:14.859 demo[20683] File :main.m 2013-09-14 04:46:14.859 demo[20683] Date :Sep 14 2013 2013-09-14 04:46:14.859 demo[20683] Time :04:46:14 2013-09-14 04:46:14.859 demo[20683] Line :8 2013-09-14 04:46:14.859 demo[20683] ANSI :1 Preprocessor Operators The Objective-C preprocessor offers following operators to help you in creating macros − Macro Continuation () A macro usually must be contained on a single line. The macro continuation operator is used to continue a macro that is too long for a single line. For example − #define message_for(a, b) NSLog(@#a ” and ” #b “: We love you!n”) Stringize (#) The stringize or number-sign operator (”#”), when used within a macro definition, converts a macro parameter into a string constant. This operator may be used only in a macro that has a specified argument or parameter list. For example − Live Demo #import <Foundation/Foundation.h> #define message_for(a, b) NSLog(@#a ” and ” #b “: We love you!n”) int main(void) { message_for(Carole, Debra); return 0; } When the above code is compiled and executed, it produces the following result − 2013-09-14 05:46:14.859 demo[20683] Carole and Debra: We love you! Token Pasting (##) The token-pasting operator (##) within a macro definition combines two arguments. It permits two separate tokens in the macro definition to be joined into a single token. For example − Live Demo #import <Foundation/Foundation.h> #define tokenpaster(n) NSLog (@”token” #n ” = %d”, token##n) int main(void) { int token34 = 40; tokenpaster(34); return 0; } When the above code is compiled and executed, it produces the following result − 2013-09-14 05:48:14.859 demo[20683] token34 = 40 How it happened, because this example results in the following actual output from the preprocessor − NSLog (@”token34 = %d”, token34); This example shows the concatenation of token##n into token34 and here we have used both stringize and token-pasting. The defined() Operator The preprocessor defined operator is used in constant expressions to determine if an identifier is defined using #define. If the specified identifier is defined, the value is true (non-zero). If the symbol is not defined, the value is false (zero). The defined operator is specified as follows − Live Demo #import <Foundation/Foundation.h> #if !defined (MESSAGE) #define MESSAGE “You wish!” #endif int main(void) { NSLog(@”Here is the message: %sn”, MESSAGE); return 0; } When the above code is compiled and executed, it produces the following result − 2013-09-14 05:48:19.859 demo[20683] Here is the message: You wish! Parameterized Macros One of the powerful functions of the OCPP is the ability to simulate functions using parameterized macros. For example, we might have some code to square a number as follows − int square(int x) { return x * x; } We can rewrite above code using a macro as follows − #define square(x) ((x) * (x)) Macros with arguments must be defined using the #define directive before they can be used. The argument list is enclosed in parentheses and must immediately follow the macro name. Spaces are not allowed between macro name and open parenthesis. For example − Live Demo
Category: Computer Programming
Objective-C – Numbers
Objective-C Numbers ”; Previous Next In Objective-C programming language, in order to save the basic data types like int, float, bool in object form, Objective-C provides a range of methods to work with NSNumber and important ones are listed in following table. Sr.No. Method & Description 1 + (NSNumber *)numberWithBool:(BOOL)value Creates and returns an NSNumber object containing a given value, treating it as a BOOL. 2 + (NSNumber *)numberWithChar:(char)value Creates and returns an NSNumber object containing a given value, treating it as a signed char. 3 + (NSNumber *)numberWithDouble:(double)value Creates and returns an NSNumber object containing a given value, treating it as a double. 4 + (NSNumber *)numberWithFloat:(float)value Creates and returns an NSNumber object containing a given value, treating it as a float. 5 + (NSNumber *)numberWithInt:(int)value Creates and returns an NSNumber object containing a given value, treating it as a signed int. 6 + (NSNumber *)numberWithInteger:(NSInteger)value Creates and returns an NSNumber object containing a given value, treating it as an NSInteger. 7 – (BOOL)boolValue Returns the receiver”s value as a BOOL. 8 – (char)charValue Returns the receiver”s value as a char. 9 – (double)doubleValue Returns the receiver”s value as a double. 10 – (float)floatValue Returns the receiver”s value as a float. 11 – (NSInteger)integerValue Returns the receiver”s value as an NSInteger. 12 – (int)intValue Returns the receiver”s value as an int. 13 – (NSString *)stringValue Returns the receiver”s value as a human-readable string. Here is a simple example for using NSNumber which multiplies two numbers and returns the product. Live Demo #import <Foundation/Foundation.h> @interface SampleClass:NSObject – (NSNumber *)multiplyA:(NSNumber *)a withB:(NSNumber *)b; @end @implementation SampleClass – (NSNumber *)multiplyA:(NSNumber *)a withB:(NSNumber *)b { float number1 = [a floatValue]; float number2 = [b floatValue]; float product = number1 * number2; NSNumber *result = [NSNumber numberWithFloat:product]; return result; } @end int main() { NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; SampleClass *sampleClass = [[SampleClass alloc]init]; NSNumber *a = [NSNumber numberWithFloat:10.5]; NSNumber *b = [NSNumber numberWithFloat:10.0]; NSNumber *result = [sampleClass multiplyA:a withB:b]; NSString *resultString = [result stringValue]; NSLog(@”The product is %@”,resultString); [pool drain]; return 0; } Now when we compile and run the program, we will get the following result. 2013-09-14 18:53:40.575 demo[16787] The product is 105 Print Page Previous Next Advertisements ”;
OAuth 2.0 – Quick Guide
OAuth 2.0 – Quick Guide ”; Previous Next OAuth 2.0 – Overview What is OAuth 2.0? OAuth is an open authorization protocol, which allows accessing the resources of the resource owner by enabling the client applications on HTTP services such as Facebook, GitHub, etc. It allows sharing of resources stored on one site to another site without using their credentials. It uses username and password tokens instead. OAuth 2.0 is developed by the IETF OAuth Working Group, published in October 2012. Why Use OAuth 2.0? You can use OAuth 2.0 to read data of a user from another application. It supplies the authorization workflow for web, desktop applications, and mobile devices. It is a server side web app that uses authorization code and does not interact with user credentials. Features of OAuth 2.0 OAuth 2.0 is a simple protocol that allows to access resources of the user without sharing passwords. It provides user agent flows for running clients application using a scripting language, such as JavaScript. Typically, a browser is a user agent. It accesses the data using tokens instead of using their credentials and stores data in online file system of the user such as Google Docs or Dropbox account. Advantages of OAuth 2.0 OAuth 2.0 is a very flexible protocol that relies on SSL (Secure Sockets Layer that ensures data between the web server and browsers remain private) to save user access token. OAuth 2.0 relies on SSL which is used to ensure cryptography industry protocols and are being used to keep the data safe. It allows limited access to the user”s data and allows accessing when authorization tokens expire. It has ability to share data for users without having to release personal information. It is easier to implement and provides stronger authentication. Disadvantages of OAuth 2.0 If you are adding more extension at the ends in the specification, it will produce a wide range of non-interoperable implementations, which means you have to write separate pieces of code for Facebook, Google, etc. If your favorite sites are connected to the central hub and the central account is hacked, then it will lead to serious effects across several sites instead of just one. OAuth 2.0 – Architecture In this chapter, we will discuss the architectural style of OAuth 2.0. Step 1 − First, the user accesses resources using the client application such as Google, Facebook, Twitter, etc. Step 2 − Next, the client application will be provided with the client id and client password during registering the redirect URI (Uniform Resource Identifier). Step 3 − The user logs in using the authenticating application. The client ID and client password is unique to the client application on the authorization server. Step 4 − The authenticating server redirects the user to a redirect Uniform Resource Identifier (URI) using authorization code. Step 5 − The user accesses the page located at redirect URI in the client application. Step 6 − The client application will be provided with the authentication code, client id and client password, and send them to the authorization server. Step 7 − The authenticating application returns an access token to the client application. Step 8 − Once the client application gets an access token, the user starts accessing the resources of the resource owner using the client application. OAuth 2.0 has various concepts, which are briefly explained in the following table. Sr.No. Concept & Description 1 Terminology OAuth provides some additional terms to understand the concepts of authorization. 2 Web Server Web server delivers the web pages and uses HTTP to serve the files that forms the web pages to the users. 3 User-Agent The user agent application is used by client applications in the user”s device, which acts as the scripting language instance. 4 Native Application Native application can be used as an instance of desktop or mobile phone application, which uses the resource owner password credentials. OAuth 2.0 – Client Credentials The client credentials can be used as an authorization grant when the client is the resource owner, or when the authorization scope is limited to protected resources under the control of the client. The client requests an access token only with the help of client credentials. The client credentials authorization flow is used to acquire access token to authorize API requests. Using client credentials authorization, access token which is acquired, only grants permission for your client application to search and get catalog documents. The following figure depicts the Client Credentials Flow. The flow illustrated in the above figure consists of the following steps − Step 1 − The client authenticates with the authorization server and makes a request for access token from the token endpoint. Step 2 − The authorization server authenticates the client and provides access token if it”s valid and authorized. The following table lists the concepts of Client Credentials. Sr.No. Concept & Description 1 Obtaining End-User Authorization The authorization end point is typically URI on the authorization server in which the resource owner logs in and permits to access the data to the client application. 2 Authorization Response The authorization response can be used to get the access token for accessing the owner resources in the system using the authorization code. 3 Error Response and Codes The authorization server responds with a HTTP 400 or 401 (bad request) status codes, if an error occurs during authorization.
OAuth 2.0 – IANA Considerations ”; Previous Next IANA stands for Internet Assigned Numbers Authority which provides the information about the registration values related to the Remote Authentication Dial In User Service (RADIUS). IANA includes the following considerations − OAuth Access Token Types Registry OAuth access tokens are registered by experts with required specification. If they are satisfied with the registration, only then they will publish the specification. The registration request will be sent to the @ietf.org for reviewing with the subject (“Request for access token type: example”). Experts will either reject or accept the request within 14 days of the request. Registration Template The registration template contains the following specifications − Type Name − It is the name of the request. Token Endpoint Response Parameters − The additional access token response parameter will be registered separately in OAuth parameters registry. HTTP Authentication Scheme − The HTTP authentication scheme can be used to authenticate the resources by using the access token. Change Controller − Give the state name as “IETF” for standard track RFCs, and for others, use the name of the responsible party. Specification Document − The specification document contains the parameter that can be used to retrieve a copy of the document. OAuth Parameters Registry OAuth parameters registry contains registration of authorization endpoint request or response, token endpoint request or response by the experts with the required specification. The registration request will be sent to the experts and if they are satisfied with registration, then they will publish the specification. Registration Template The registration template contains specifications such as Type Name, Change Controller and Specification Document as defined in the above OAuth Access Token Types Registry section, except the following specification − Parameter Usage Location − It specifies the location of the parameter such as authorization request or response, token request or response. Initial Registry Contents The following table shows OAuth parameters registry containing the initial contents − Sr.No. Parameter Name & Usage Location Change Controller Specification Document 1 client_id authorization request, token request IETF RFC 6749 2 client_secret token request IETF RFC 6749 3 response_type authorization_request IETF RFC 6749 4 redirect_uri authorization request, authorization IETF RFC 6749 5 scope authorization request or response, token request or response IETF RFC 6749 6 state authorization request or response IETF RFC 6749 7 code token request, authorization response IETF RFC 6749 8 error_description authorization response, token response IETF RFC 6749 9 error_uri authorization response, token response IETF RFC 6749 10 grant_type token request IETF RFC 6749 11 access_token authorization response, token response IETF RFC 6749 12 token_type authorization response, token response IETF RFC 6749 13 expires_in authorization response, token response IETF RFC 6749 14 username token request IETF RFC 6749 15 password token request IETF RFC 6749 16 refresh_token token request, token response IETF RFC 6749 OAuth Authorization Endpoint Response Type Registry This can be used to define OAuth Authorization Endpoint Response Type Registry. The response types are registered by experts with the required specification and if they are satisfied with the registration, only then they will publish the specification. The registration request will be sent to the @ietf.org for reviewing. The experts will either reject or accept the request within 14 days of the request. Registration Template The registration template contains specifications such as Type Name, Change Controller and Specification Document as defined in the above OAuth Access Token Types Registry section. Initial Registry Contents The following table shows the authorization endpoint response type registry containing the initial contents. Sr.No. Parameter Name Change Controller Specification Document 1 code IETF RFC 6749 2 token IETF RFC 6749 OAuth Extensions Error Registry This can be used to define OAuth Extensions Error Registry. The error codes along with protocol extensions such as grant types, token types, etc. are registered by experts with the required specification. If they are satisfied with the registration, then they will publish the specification. The registration request will be sent to the @ietf.org for reviewing with subject (“Request for error code: example”). Experts will either reject or accept the request within 14 days of the request. Registration Template The registration template contains specifications such as Change Controller and Specification Document as defined in the above OAuth Access Token Types Registry section, except the following specifications − Error Name − It is the name of the request. Error Usage Location − It specifies the location of the error such as authorization code grant error response, implicit grant response or token error response, etc, which specifies where the error can be used. Related Protocol Extension − You can use protocol extensions such as extension grant type, access token type, extension parameter, etc. Print Page Previous Next Advertisements ”;
OAuth 2.0 – Extensibility
OAuth 2.0 – Extensibility ”; Previous Next There are two ways in which the access token types can be defined − By registering in the access token type”s registry. By using a unique absolute URI (Uniform Resource Identifier) as its name. Defining New Endpoint Parameters Parameter names must obey the param-name ABNF (Augmented Backus-Naur Form is a metalanguage based on Backus-Naur Form consisting of its own syntax and derivation rules) and the syntax of parameter values must be well-defined. param-name = 1* name-char name-char = “-” / “.” / “_” / DIGIT / ALPHA Defining New Authorization Grant Types New authorization grant types can be assigned a distinct absolute URI for use, with the help of “grant_type” parameter. The extension grant type must be registered in the OAuth parameters registry, if it requires additional token endpoint parameters. Defining New Authorization Endpoint Response Types response-type = response-name *(SP response-name) response-name = 1* response-char response-char = “_” / DIGIT / ALPHA The response type is compared as space-delimited list of values, if it has one or more space characters where the order of the values does not matter and only one order of value can be registered. Defining Additional Error Codes The extension error codes must be registered, if the extensions they use are either a registered access token, or a registered endpoint parameter. The error code must obey the error ABNF (Augmented Backus-Naur Form) and when possible it should be prefixed by a name identifying it. error = 1 * error_char error-char = %x20-21 / %x23-5B / 5D-7E Print Page Previous Next Advertisements ”;
Objective-C Data Encapsulation ”; Previous Next All Objective-C programs are composed of the following two fundamental elements − Program statements (code) − This is the part of a program that performs actions and they are called methods. Program data − The data is the information of the program which is affected by the program functions. Encapsulation is an Object-Oriented Programming concept that binds together the data and functions that manipulate the data and that keeps both safe from outside interference and misuse. Data encapsulation led to the important OOP concept of data hiding. Data encapsulation is a mechanism of bundling the data and the functions that use them, and data abstraction is a mechanism of exposing only the interfaces and hiding the implementation details from the user. Objective-C supports the properties of encapsulation and data hiding through the creation of user-defined types, called classes. For example − @interface Adder : NSObject { NSInteger total; } – (id)initWithInitialNumber:(NSInteger)initialNumber; – (void)addNumber:(NSInteger)newNumber; – (NSInteger)getTotal; @end The variable total is private and we cannot access from outside the class. This means that they can be accessed only by other members of the Adder class and not by any other part of your program. This is one way encapsulation is achieved. Methods inside the interface file are accessible and are public in scope. There are private methods, which are written with the help of extensions, which we will learn in upcoming chapters. Data Encapsulation Example Any Objective-C program where you implement a class with public and private members variables is an example of data encapsulation and data abstraction. Consider the following example − Live Demo #import <Foundation/Foundation.h> @interface Adder : NSObject { NSInteger total; } – (id)initWithInitialNumber:(NSInteger)initialNumber; – (void)addNumber:(NSInteger)newNumber; – (NSInteger)getTotal; @end @implementation Adder -(id)initWithInitialNumber:(NSInteger)initialNumber { total = initialNumber; return self; } – (void)addNumber:(NSInteger)newNumber { total = total + newNumber; } – (NSInteger)getTotal { return total; } @end int main(int argc, const char * argv[]) { NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; Adder *adder = [[Adder alloc]initWithInitialNumber:10]; [adder addNumber:5]; [adder addNumber:4]; NSLog(@”The total is %ld”,[adder getTotal]); [pool drain]; return 0; } When the above code is compiled and executed, it produces the following result − 2013-09-22 21:17:30.485 DataEncapsulation[317:303] The total is 19 Above class adds numbers together and returns the sum. The public members addNum and getTotal are the interfaces to the outside world and a user needs to know them to use the class. The private member total is something that is hidden from the outside world, but is needed for the class to operate properly. Designing Strategy Most of us have learned through bitter experience to make class members private by default unless we really need to expose them. That”s just good encapsulation. It”s important to understand data encapsulation since it”s one of the core features of all Object-Oriented Programming (OOP) languages including Objective-C. Print Page Previous Next Advertisements ”;
OAuth 2.0 – Accessing a Protected Resource ”; Previous Next The client provides an access token to the resource server to access protected resources. The resource server must validate and verify that the access token is valid and has not expired. There are two standard ways of sending credentials − Bearer Token − The access token can only be placed in POST request body or GET URL parameter as a fallback option in the authorization HTTP header. They are included in the authorization header as follows − Authorization: Bearer [token-value] For Example − GET/resource/1 HTTP /1.1 Host: example.com Authorization: Bearer abc… MAC − A cryptographic Message Authentication Code (MAC) is computed using the elements of the request and is sent to the authorization header. Upon receiving the request, the MAC is then compared and computed by the resource owner. The following table shows the concepts of accessing protected resource. Sr.No. Concept & Description 1 Authenticated Requests It is used to get the authorization code token for accessing the owner resources in the system. 2 The WWW-Authenticate Response Header Field The resource server includes the “WWW-Authenticate” response header field, if the protected resource request contains an invalid access token. Print Page Previous Next Advertisements ”;
Objective-C – Error Handling
Objective-C Error Handling ”; Previous Next In Objective-C programming, error handling is provided with NSError class available in Foundation framework. An NSError object encapsulates richer and more extensible error information than is possible using only an error code or error string. The core attributes of an NSError object are an error domain (represented by a string), a domain-specific error code and a user info dictionary containing application specific information. NSError Objective-C programs use NSError objects to convey information about runtime errors that users need to be informed about. In most cases, a program displays this error information in a dialog or sheet. But it may also interpret the information and either ask the user to attempt to recover from the error or attempt to correct the error on its own NSError Object consists of − Domain − The error domain can be one of the predefined NSError domains or an arbitrary string describing a custom domain and domain must not be nil. Code − The error code for the error. User Info − The userInfo dictionary for the error and userInfo may be nil. The following example shows how to create a custom error NSString *domain = @”com.MyCompany.MyApplication.ErrorDomain”; NSString *desc = NSLocalizedString(@”Unable to complete the process”, @””); NSDictionary *userInfo = @{ NSLocalizedDescriptionKey : desc }; NSError *error = [NSError errorWithDomain:domain code:-101 userInfo:userInfo]; Here is complete code of the above error sample passed as reference to an pointer − Live Demo #import <Foundation/Foundation.h> @interface SampleClass:NSObject -(NSString *) getEmployeeNameForID:(int) id withError:(NSError **)errorPtr; @end @implementation SampleClass -(NSString *) getEmployeeNameForID:(int) id withError:(NSError **)errorPtr { if(id == 1) { return @”Employee Test Name”; } else { NSString *domain = @”com.MyCompany.MyApplication.ErrorDomain”; NSString *desc =@”Unable to complete the process”; NSDictionary *userInfo = [[NSDictionary alloc] initWithObjectsAndKeys:desc, @”NSLocalizedDescriptionKey”,NULL]; *errorPtr = [NSError errorWithDomain:domain code:-101 userInfo:userInfo]; return @””; } } @end int main() { NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; SampleClass *sampleClass = [[SampleClass alloc]init]; NSError *error = nil; NSString *name1 = [sampleClass getEmployeeNameForID:1 withError:&error]; if(error) { NSLog(@”Error finding Name1: %@”,error); } else { NSLog(@”Name1: %@”,name1); } error = nil; NSString *name2 = [sampleClass getEmployeeNameForID:2 withError:&error]; if(error) { NSLog(@”Error finding Name2: %@”,error); } else { NSLog(@”Name2: %@”,name2); } [pool drain]; return 0; } In the above example, we return a name if the id is 1, otherwise we set the user-defined error object. When the above code is compiled and executed, it produces the following result − 2013-09-14 18:01:00.809 demo[27632] Name1: Employee Test Name 2013-09-14 18:01:00.809 demo[27632] Error finding Name2: Unable to complete the process Print Page Previous Next Advertisements ”;
OAuth 2.0 – Discussion
Discuss OAuth 2.0 ”; Previous Next OAuth 2.0 is an open authorization protocol, which allows accessing the resources of the resource owner by enabling the client applications on HTTP services such as Facebook, GitHub, etc. It allows sharing of resources stored on one site to another site without using their credentials. It uses username and password tokens instead. Print Page Previous Next Advertisements ”;
Objective-C – Polymorphism
Objective-C Polymorphism ”; Previous Next The word polymorphism means having many forms. Typically, polymorphism occurs when there is a hierarchy of classes and they are related by inheritance. Objective-C polymorphism means that a call to a member function will cause a different function to be executed depending on the type of object that invokes the function. Consider the example, we have a class Shape that provides the basic interface for all the shapes. Square and Rectangle are derived from the base class Shape. We have the method printArea that is going to show about the OOP feature polymorphism. Live Demo #import <Foundation/Foundation.h> @interface Shape : NSObject { CGFloat area; } – (void)printArea; – (void)calculateArea; @end @implementation Shape – (void)printArea { NSLog(@”The area is %f”, area); } – (void)calculateArea { } @end @interface Square : Shape { CGFloat length; } – (id)initWithSide:(CGFloat)side; – (void)calculateArea; @end @implementation Square – (id)initWithSide:(CGFloat)side { length = side; return self; } – (void)calculateArea { area = length * length; } – (void)printArea { NSLog(@”The area of square is %f”, area); } @end @interface Rectangle : Shape { CGFloat length; CGFloat breadth; } – (id)initWithLength:(CGFloat)rLength andBreadth:(CGFloat)rBreadth; @end @implementation Rectangle – (id)initWithLength:(CGFloat)rLength andBreadth:(CGFloat)rBreadth { length = rLength; breadth = rBreadth; return self; } – (void)calculateArea { area = length * breadth; } @end int main(int argc, const char * argv[]) { NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; Shape *square = [[Square alloc]initWithSide:10.0]; [square calculateArea]; [square printArea]; Shape *rect = [[Rectangle alloc] initWithLength:10.0 andBreadth:5.0]; [rect calculateArea]; [rect printArea]; [pool drain]; return 0; } When the above code is compiled and executed, it produces the following result − 2013-09-22 21:21:50.785 Polymorphism[358:303] The area of square is 100.000000 2013-09-22 21:21:50.786 Polymorphism[358:303] The area is 50.000000 In the above example based on the availability of the method calculateArea and printArea, either the method in the base class or the derived class executed. Polymorphism handles the switching of methods between the base class and derived class based on the method implementation of the two classes. Print Page Previous Next Advertisements ”;