Thursday, April 21, 2011

Simple How To Learn Objective-C For Developing Apple Software


Objective-C is an object-oriented programming language, and is a layer over the C programming language. This means that if you know how to write C, there are only a few syntax changes to learn.
In this section, we will look at how we can implement classes and instantiate objects in Objective-C. If you are unfamiliar with object-oriented programming, see Objective-C concepts.

If you have studied C, you can skip this section and proceed to the next section, A word on runtimes. However, there may be individuals that may try learning Objective-C without the parent language.[edit]


Figure 1-1  A class declaration
A class declaration

Figure 1-2  Method declaration syntax
Method declaration syntax

Basic syntax

In objective C, code is contained within functions, and a function is composed of several statements. Each statement is terminated by a semicolon. For example, a simple function to add two numbers may look like this:
int add (int a, int b)
{
    int c;
    c = a + b;
    return c;
}
This sample has the following lines:
  1. The function definition (which returns an int, is named add, and takes two parameters, both of which are integers).
  2. The opening function brace
  3. A variable declaration
  4. An assignment statement
  5. A return statement, which returns the value of c to the calling function/
  6. The closing function brace
For flow control, Objective-C uses:
  1. for (<initial>;<condition>;<increment>)
  2. while (<condition>)
  3. do ... while (<condition>)
  4. switch (<condition>)
Each statement behaves in the same way as C; they will continue execution of a loop until the condition is false (or in the case of switch, jumps to the appropriate case label and continues to the end) and can be exited early using the break or continue keywords.
Objective-C does not implement functions by default. Instead, they need to be declared by using the #include or #import preprocessor statements.

[edit]A word on runtimes

Objective-C requires what is known as a runtime system to provide you with Objective-C features. The runtime takes care of the creation, management, and destruction of objects.
If you have the gcc compiler, you should have the Objective-C runtime already installed. Otherwise, you may have to install the runtime separately. Note that gcc is a compiler collection; the full install contains not only the C compiler, but also C++, Java, Objective-C and even Fortran-95 and Ada 2005 compilers. However, it is possible to install gcc only partially, for example only the C compiler. Therefore, the Objective-C runtime may or may not be installed with gcc. Check your distribution.
Two main systems are used to run Objective-C programs:
  • the GNU runtime, which is provided as a part of gcc on Unix and Unix-like operating systems;
  • the NeXT runtime, which is provided on NeXTSTEP, OPENSTEP, and Mac OS X operating systems.
This text assumes you are using the GNU runtime, but the two runtime systems are almost identical.
This text does not cover the OPENSTEP, Cocoa, or GNUstep frameworks, but the skills learned here will be helpful when developing with those systems.

[edit]Writing classes in Objective-C

Writing an Objective-C class requires a few design decisions before we start writing any code. Say we are writing a class to represent a point called Point in a two-dimensional plane.
We need to ask ourselves two questions:
  1. What data do we need to store and use? This relates to the instance variables we need to declare.
  2. What operations do we need to perform? This relates to the methods we need to define.

For this example, we'll use double variables for the x and y coordinates. We'll define a method to get both coordinates, and we'll define a method to get their distance from the origin.

[edit]The interface

#import <objc/Object.h>
 
@interface Point : Object
{
@private
   double x;
   double y;
}
 
- (id) x: (double) x_value;
- (double) x;
- (id) y: (double) y_value;
- (double) y;
- (double) magnitude;
@end
Let's examine what each element of this interface means.
#import <objc/Object.h>
 
@interface Point : Object
The @interface line says that we begin the declaration of the Point interface. We inherit from another class called Object. Objective-C provides you with a generic class, calledObject. The Object class provides a set of methods that provide key functionality for an object to be used and recognized by the Objective-C runtime. Every object in Objective-C inherits from Object. As in C, we need to include Object's header file, Object.h, before we can use the set of methods declared in the header.
The word import means that we only include the file once. This solves problems like recursive includes.
{
@private
   double x;
   double y;
}
Anything between the braces in an interface declaration specifies the instance variables that the class has.
The @private line is a visibility modifier: it says that the instance variables after it are private, i.e. they are accessible only from the class that declares them. It is good practice to mark all your instance variables private: they contain the state of an object and they should never be changed except by the object itself.
- (id) x: (double) x_value;
The declarations for the methods come after the instance variables. This is a declaration for the method to set the x value. It's common Objective-C style to name the setter method with the same name as the variable it's setting.
The dash specifies an instance method (we'll look at these later). Then comes the name for the method (this method is called x: - note the colon), and the colon signifies an argument, called x_value, and is of type double.
The cast on the x_value argument is necessary, because unlike C, the default type is id, and not int. The type id is very special—it is a type that can hold any object whatsoever. The first cast is not strictly necessary, but should be used for clarity. The first cast tells us that the method x returns an object back.
- (double) x;
This is another method named x (no colon), but it returns a double. This is the specification for the method that gets the value of the x variable. There is no conflict with the previous method because the types are different, and the previous method takes one argument whilst this takes none.
@end
After all the methods and instance variables are specified, this symbol marks the end of the declaration.
The interface specification goes in a .h file—a header file. It's customary to call the file after the class, so we would create a file called Point.h.

[edit]The implementation

#import "Point.h"
#import <math.h>
 
@implementation Point
 
- (id) x: (double) x_value
{
   x = x_value;
   return self;
}
 
- (double) x
{
   return x;
}
 
- (id) y: (double) y_value
{
   y = y_value;
   return self;
}
 
- (double) y
{
   return y;
}
 
- (double) magnitude
{
   return sqrt(x*x+y*y);
}
 
@end
This is the implementation for the Point class. We implement the methods in the interface defined above. Let's have a look at each element of the implementation in turn.
#import "Point.h"
Again, we import Point's interface, just as we do in C.
@implementation Point
This is a marker that identifies the beginning of the implementation.
- (id) x: (double) x_value
{
   x = x_value;
   return self;
}
This is a typical method implementation. We can use the x variable directly without having to declare it since it is already declared in the interface, and is accessible only to the methods of this class. The behaviour, in general, is like an ordinary C function. Here we assign the value of the argument x_value to the instance variable x.
The function then, returns the entire, current object as modified. The keyword self represents the current object.
- (double) x
{
   return x;
}
Here is the simple method to get the value of the x variable. We simply return it.
The behaviour for the other methods should be similar to those above. The @end keyword ends the implementation.
The implementation specification goes in a .m file. It's customary to call the file after the class, so we would create a file called Point.m.

[edit]Using the objects

Since Objective-C comes from C, we write a main function to make use of the class that we just created. Here's one typical main function.
#import "Point.h"
#import <math.h>
#import <stdio.h>
 
int main(void)
{
   Point *point = [Point new];
   [point x:10.0];
   [point y:12.0];
   printf("The distance from the point (%g, %g) to the origin is %g.\n",
      [point x], [point y], [point magnitude]);
 
   return 0;
}
Let's examine what happens here.
#import "Point.h"
#import <stdio.h>
We import the interface to Point so we can use it. We import stdio.h so we can use printf.
Point *point = [Point new];
This is a typical Objective-C method call:
  • Point *point declares, technically, a pointer to an instance of type Point. Actually, it may be best to think of this merely as a variable holding a Point object, but keep the pointer idea in mind.
  • [Point new] calls a method called new. The first half before the space represents the object we call the method on. The second half is the method name and arguments. The newmethod is called a class method, because it doesn't do something with respect to an instance of a class, it does something with respect to the class itself. The new method allocates memory and initializes the object, making it ready for use. There is no need to explicitly delete an object, as Objective C keeps track of the number of references to a given object, and deallocates them as necessary.
    NOTE: The new method is shorthand for alloc and init and may not always be available. If it is not, the object can be initialized and made ready for use in the following fashion: [[Point alloc] init]







[point x:10.0];
    [point y:12.0];
These are some typical instance method calls. We call point's method x: and y:. In Objective-C terminology, we say that we send point a message to apply to the method x:.
These messages assign point's x and y variables. Recall that the x: and y: methods had in them return self;. This means that we can chain the two messages together, as follows:
[[point x:10.0] y:12.0];
The message [point x:10.0] returns an object, point, with its x variable set. Then on that object, the outer message assigns its y variable.
printf("The distance from the point (%g, %g) to the origin is %g.\n",
       [point x], [point y], [point magnitude]);
The printf statement has in it the method calls [point x], which returns the value of the x variable for printing, [point y], which does the same for the y variable for printing, and [point magnitude] which calculates the distance and returns that value.

Saturday, April 16, 2011

What is apple iPhone Operating System and iPhone Application


iPhone Operating System Overview

iOS comprises the operating system and technologies that you use to run applications natively on devices, such as iPad, iPhone, and iPod touch. Although it shares a common heritage and many underlying technologies with Mac OS X, iOS was designed to meet the needs of a mobile environment, where users’ needs are slightly different. If you have previously developed applications for Mac OS X, you will find many familiar technologies, but you’ll also find technologies that are available only on iOS, such as the Multi-Touch interface and accelerometer support.

The iOS SDK contains the code, information, and tools you need to develop, test, run, debug, and tune applications for iOS. The Xcode tools provide the basic editing, compilation, and debugging environment for your code. Xcode also provides the launching point for testing your applications on an iOS device, and in iOS Simulator—a platform that mimics the basic iOS environment but runs on your local Macintosh computer.
This article provides a high-level overview of the basic features found in iOS, to help orient you to the platform. You’ll find other articles in the iOS Dev Center to help get you up to speed quickly and to help you understand the basic process for creating iOS applications. You should use these articles to help guide your learning path for iOS.
image: Art/overview_iphonetouch.jpg

Contents:


iOS Technology Layers

The kernel in iOS is based on a variant of the same basic Mach kernel that is found in Mac OS X. On top of this kernel are the layers of services that are used to implement applications on the platform. Figure 1-1 shows a high-level overview of these layers.
Figure 1-1  iOS technology layers
This layering gives you choices when it comes to implementing your code. For example, the Core OS and Core Services layers contain the fundamental interfaces for iOS, including those used for accessing files, low-level data types, Bonjour services, network sockets, and so on. These interfaces are mostly C-based and include technologies such as Core Foundation, CFNetwork, SQLite, and access to POSIX threads and UNIX sockets among others.
As you move into the upper layers, you find more advanced technologies that use interfaces based on a mixture of C and Objective-C. For example, the Media layer contains the fundamental technologies used to support 2D and 3D drawing, audio, and video. This layer includes the C-based technologies OpenGL ES, Quartz, and Core Audio. It also contains Core Animation, which is an advanced Objective-C based animation engine.
In the Cocoa Touch layer, most of the technologies use Objective-C. The frameworks at these layers provide the fundamental infrastructure used by your application. For example, the Foundation framework provides object-oriented support for collections, file management, network operations, and more. The UIKit framework provides the visual infrastructure for your application, including classes for windows, views, controls, and the controllers that manage those objects. Other frameworks at this level give you access to the user’s contact and photo information and to the accelerometers and other hardware features of the device.
The starting point for any new project is the Cocoa Touch layer, and the UIKit framework in particular. When deciding what additional technologies to use, you should start with frameworks in the higher-level layers. The higher-level frameworks make it easy to support standard system behaviors with the least amount of effort on your part. You should fall back to the lower-level frameworks only if you want to implement custom behavior that is not provided at a higher level.
For a more detailed overview of the technologies in iOS, see iOS Technology Overview.

Writing Code for iOS

The iOS SDK supports the creation of graphically-oriented applications that run natively in iOS. The applications you create reside on the user’s Home screen, along with the other system applications, such as Photos, Weather, and Clock. While running, your application occupies the entire screen and is the focus of the user’s attention. There is no concept of separate document windows for displaying content. Instead, all of the application’s data is displayed in a single window.
The event-handling model in iOS represents a significant departure from traditional desktop applications. Instead of relying on the traditional mouse and keyboard events, iOS introduces the idea of touch events. A touch event can occur at any time and in combination with one or more additional touch events. Touches can be used to detect simple interactions with content, such as selecting or dragging items, or they can be used to detect complex gestures and interactions, such as swipes or the pinch-open and pinch-close gestures (used, for example, to zoom in and out in the Photos application).
Beyond considering the basic structure of your application, you need to think about how users will actually use it. iOS applications should be clean, and focused on what the user needs in the moment. Remember that users who are on-the-go want to get at information quickly and not spend a lot of time looking through several layers of screens. Providing a simple layout that highlights the key information the user needs is important. For games and other fun applications, you should also consider how the users might want to interact with your application and take advantage of technologies such as the accelerometers and camera where appropriate.
As you start development, the frameworks you want to use initially are the Foundation and UIKit frameworks. These frameworks provide the key services used by all iOS applications. As you refine your application, you should investigate the other frameworks in the system to see what services they offer. The documentation for each framework includes links to relevant conceptual materials to help you learn more about how to use that framework.
For information about the Foundation and UIKit frameworks, see Foundation Framework Reference and UIKit Framework Reference.

Where to Start

Creating simple applications that run on iOS is relatively easy with the built-in project templates provided by Xcode, but creating applications that do something useful and look nice requires you to spend some time reading through the available documentation. At a minimum, you should take the time to read through the other orientation articles in the iOS Dev Center, which explore the tools and process for creating applications.
If you are completely new to iOS and to Mac OS X, taking the time to understand the basic design patterns and conventions of iOS is critical to writing code for the platform. Applications operate best in iOS when they take advantage of the power the frameworks provide. If you spend time trying to work around the basic framework behaviors, you may find creating your application much more difficult than simply learning the basic design patterns in use. The basic information that every iPhone developer needs to know is in Cocoa Fundamentals Guide. This document covers the basics of the Objective-C language and the programming conventions and design patterns used by UIKit and many other system frameworks.
Once you understand the basic conventions you use to create iOS applications, you can refer to iOS Application Programming Guide for specific details on the development process. This book provides key conceptual and task-based information on how to write iPhone applications, including examples of how to display a user interface, handle events, and take advantage of key iOS features. It also describes the overall development process and explains how you use Xcode to build and run your applications.
In addition to iOS Application Programming Guide, you should also look through the available sample code. iOS ships with a number of full-featured samples that show you how to use the available technologies to create real-world applications. You can use these samples as a starting point for your own applications or you can look at them to learn more about how you use specific features.

Thursday, April 14, 2011

How to Set Up Apple Push Notification in iPhone


Programming Apple Push Notification Services

Section Feature image
POSTED BY WEIMENGLEE 1 YEAR 13 WEEKS AGO
Bookmark and Share

One of the key limitations of the iPhone is its constraint on running applications in the background. Because of this, applications cannot keep running in the background when the user switches to another application. So, applications that require a constant state of connectivity (such as social networking applications) will not be able to receive timely updates.
To remedy this limitation, Apple released the Apple Push Notification Service (APNs). The APNs is a service that allows your device to be constantly connected to Apple's push notification server. When you want to send a push notification to an application installed on the users' devices, you (the provider) can contact the APNs so that it can deliver a push message to the particular application installed on the intended device.
In this article, you will learn how to perform the various steps needed to create an iPhone application that uses the APNs.

Generating a Certificate Request

The first step to using the APNs is to generate a certificate request file so that you can use it to request for a development SSL certificate later on.
1. Launch the Keychain Access application in your Mac OS X.
2. Select Keychain Access'Certificate Assistant'Request a Certificate From a Certificate Authority (see Figure 1):

Figure 1. Generating a certificate request
3. Enter the information required and check the Saved to disk option. Click Continue (see Figure 2).

Figure 2. Saving the certificate request to disk
4. Save the certificate request using the suggested name and click Save (see Figure 3): Click Done in the next screen.

Figure 3. Naming the certificate request

Creating an App ID

Each iPhone applications that uses the APNs must have a unique application ID that uniquely identifies itself. In this step, you will learn how to create an App ID for push notification.
1. Sign in to the iPhone Developer Program at: http://developer.apple.com/iphone/. Click on the iPhone Developer Program Portal on the right of the page (see Figure 4).

Figure 4. Launching the iPhone Developer Program Portal
2. You should see the welcome page (see Figure 5).

Figure 5. The welcome screen of the iPhone Developer Program Portal
3. Click on the App IDs tab on the left and then click on the New App ID button (see Figure 6).

Figure 6. Clicking on the App ID tab
4. Enter "PushAppID" for the Description and select Generate New for the Bundle Seed ID. For the Bundle Identifier, enter net.learn2develop.MyPushApp. Click Submit (see Figure 7).

Figure 7. Creating a new App ID
5. You should now see the App ID that you have created (together with those you have previously created) (see Figure 8).

Figure 8. Viewing the newly created App ID

Configuring an App ID for Push Notifications

Once an App ID is created, you need to configure it for push notifications.
1. To configure an App ID for push notification, you need to click the Configure link displayed to the right of the App ID. You will now see the option (see Figure 9).

Figure 9. Configuring an App ID for push notification service
Check the Enable for Apple Push Notification service option and click the Configure button displayed to the right of the Development Push SSL Certificate.
2. You will now see the Apple Push Notification service SSL Certificate Assistant screen. Click Continue (see Figure 10).

Figure 10. The Apple Push Notification service SSL Certificate Assistant screen
3. Click the Choose File button to locate the Certificate Request file that you have saved earlier. Click Generate (see Figure 11).

Figure 11. Generating the SSL certificate
4. Your SSL Certificate will now be generated. Click Continue (see Figure 12).

Figure 12. The APNs SSL certificate that is generated
5. Click the Download Now button to download the SSL Certificate. Click Done (see Figure 13).

Figure 13. Downloading the certificate generated
6. The SSL Certificate that you download is named aps.developer.identity.cer. Double-click on it to install it in the Keychain Access application (see Figure 14). The SSL certificate will be used by your provider application so that it can contact the APNs to send push notifications to your applications.

Figure 14. Installing the generated certificate into the Keychain Access application

Creating a Provisioning Profile

The next step is to create a provisioning profile so that your application can be installed onto a real device.
1. Back in the iPhone Development Program Portal, click on the Provisioning tab and click on the New Profile button (see Figure 15).

Figure 15. Selecting the Provisioning tab
2. Type in MyDevicesProfile as the profile name. Select PushAppID as the App ID. Finally, check all the devices that you want to provision (you can register these devices with the iPhone Developer Program Portal through the Devices tab). Click Submit (see Figure 16).

Figure 16. Creating a new provisioning profile
3. The provisioning profile will now be pending approval. After a while, you will see it appear. Click on the Download button to download the provisioning profile (see Figure 17).

Figure 17. Pending the approval of the provisioning profile
4. The downloaded provisioning profile is named MyDevicesProfile.mobileprovision.

Provisioning a Device

With the provision profile created, you will now install it onto a real device.
1. Connect your iPhone or iPod Touch to your Mac.
2. Drag and drop the downloaded MyDevicesProfile.mobileprovision file onto the Xcode icon on the Dock.
3. Launch the Organizer application from within Xcode and select the device currently connected to your Mac. You should see the MyDevicesProfile installed on the device (see Figure 18).

Figure 18. Viewing the installed provisioning profile

Creating the iPhone Application

1. In Xcode, create a new View-Based Application project and name it as ApplePushNotification.
2. Drag and drop a WAV file (shown as beep.wav in this example) onto the Resources folder in Xcode (see Figure 19).

Figure 19. Adding a WAV file to the project
3. Expand on the Targets item in Xcode and select the ApplePushNotification item. Press Command-I. In the Info window, click the Properties tab (see Figure 20).

Figure 20. Entering the App ID for the application
In the Identifier textbox, type <net.learn2develop.MyPushApp.
4. Click on the Build tab and type "Code Signing" in the search box. In the Any iPhone OS Device item, select the profile as shown in Figure 21:

Figure 21. Selecting the profile for code signing
5. In the ApplePushNotificationAppDelegate.m file, type the following code in bold:
#import "ApplePushNotificationAppDelegate.h"
#import "ApplePushNotificationViewController.h"
 
@implementation ApplePushNotificationAppDelegate
 
@synthesize window;
@synthesize viewController;
 
- (void)applicationDidFinishLaunching:(UIApplication *)application {    
    [window addSubview:viewController.view];
    [window makeKeyAndVisible];
 
    NSLog(@"Registering for push notifications...");    
    [[UIApplication sharedApplication] 
        registerForRemoteNotificationTypes:
        (UIRemoteNotificationTypeAlert | 
         UIRemoteNotificationTypeBadge | 
         UIRemoteNotificationTypeSound)];
 
}
 
- (void)application:(UIApplication *)app didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken { 
 
    NSString *str = [NSString 
        stringWithFormat:@"Device Token=%@",deviceToken];
    NSLog(str);
 
}
 
- (void)application:(UIApplication *)app didFailToRegisterForRemoteNotificationsWithError:(NSError *)err { 
 
    NSString *str = [NSString stringWithFormat: @"Error: %@", err];
    NSLog(str);    
 
}
 
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
 
    for (id key in userInfo) {
        NSLog(@"key: %@, value: %@", key, [userInfo objectForKey:key]);
    }    
 
}
 
- (void)dealloc {
    [viewController release];
    [window release];
    [super dealloc];
}
 
@end
6. Press Command-R to test the application on a real device. Press Shift-Command-R in Xcode to display the Debugger Console window. Observe carefully the device token that is printed (see Figure 22). In the figure below, the token is:38c866dd bb323b39 ffa73487 5e157ee5 a85e0b7c e90d56e9 fe145bcc 6c2c594b. Record down this device token (you might want to cut and paste it into a text file).

Figure 22. Viewing the device token for push notification
7. If you go to the Settings application on your iPhone/iPod Touch, you will notice that you now have the Notifications item (see Figure 23).

Figure 23. Viewing the Notifications item in the Settings application

Creating the Push Notification Provider

A Push Notification provider is an application written by the application's developer to send push notifications to the iPhone application through the APNs.
Here are the basic steps to send push notifications to your applications via the Apple Push Notification Service (APNs):
1. Communicate with the APNs using the SSL certificate you have created earlier.
2. Construct the payload for the message you want to send.
3. Send the push notification containing the payload to the APNs.
The APNs is a stream TCP socket that your provider can communicate using a SSL secured communication channel. You send the push notification (containing the payload) as a binary stream. Once connected to the APNs, you should maintain the connection and send as many push notifications as you want within the duration of the connection.
Tip: Refrain from opening and closing the connections to the APNs for each push notification that you want to send. Rapid opening and closing of connections to the APNs will be deemed as a Denial-of-Service (DOS) attack and may prevent your provider from sending push notifications to your applications.
The format of a push notification message looks like Figure 24 (figure from Apple's documentation):

Figure 24. Format of a push notification message
For more details, please refer to Apple Push Notification Service Programming Guide.
The payload is a JSON formatted string (maximum 256 bytes) carrying the information you want to send to your application. An example of a payload looks like this:
{
    "aps": { 
        "alert" : "You got a new message!" ,
        "badge" : 5, 
        "sound" : "beep.wav"},
     "acme1" : "bar", 
     "acme2" : 42
}
To save yourself the trouble in developing a push notification provider from scratch, you can use the PushMeBabyapplication (for Mac OS X) written by Stefan Hafeneger (Get it here).
1. Open the PushMeBaby application in Xcode.
2. Right-click on the Resources folder in Xcode and select Add Existing Files…. Select theaps.developer.identity.cer file that you have downloaded earlier (see Figure 25).

Figure 25. Adding the SSL certificate to the application
3. In the ApplicationDelegate.m file, modify the code as shown in bold below:
- (id)init {
    self = [super init];
    if(self != nil) {
        self.deviceToken = @"38c866dd bb323b39 ffa73487 5e157ee5 a85e0b7c e90d56e9 fe145bcc 6c2c594b";
 
        self.payload = @"{\"aps\":{\"alert\":\"You got a new message!\",\"badge\":5,\"sound\":\"beep.wav\"},\"acme1\":\"bar\",\"acme2\":42}";
 
        self.certificate = [[NSBundle mainBundle] 
            pathForResource:@"aps_developer_identity" ofType:@"cer"];
    }
    return self;
}
4. Press Command-R to test the application. You will be asked to grant access to the certificate. Click Always Allow (see Figure 26):

Figure 26. Granting access to the SSL certificate
On the iPhone/iPod Touch, ensure that the ApplePushNotification application is not running. To send a message to the device, click the Push button. The server essentially sends the following message to the Apple Push Notification server:
{
    "aps": { 
        "alert" : "You got a new message!" ,
        "badge" : 5, 
        "sound" : "beep.wav"},
     "acme1" : "bar", 
     "acme2" : 42
}
5. If the message is pushed correctly, you should see the notification as shown in Figure 27.

Figure 27. Receiving a Push Notification message
6. If you now debug the ApplePushNotification application by pressing Command-R and send a push message from the PushMeBaby application, the Debugger Console window will display the following outputs:
2009-11-24 21:11:49.182 ApplePushNotification[1461:207] key: acme1, value: bar
2009-11-24 21:11:49.187 ApplePushNotification[1461:207] key: aps, value: {
    alert = "You got a new message!";
    badge = 5;
    sound = "beep.wav";
}
2009-11-24 21:11:49.191 ApplePushNotification[1461:207] key: acme2, value: 42

Summary

In this article, you have seen the various steps required to build an iPhone application that utilizes Apple's Push Notification service. I am interested to know how you are using the APNs for your application. Use the comment feature below to share with us!


iPhone Local Notifications

Local notifications :
Local notifications are used to notify user that application is having some updates,
while application is not running in foreground. We can display an alert message or badge on application icon. Local notifications can play sound when alert message or badge is shown.
We can use local notification to remind our daily or monthly tasks at particular time like water plants, pay electricity bill, attend seminar , prepare for presentation etc. In these cases we can use local notification.
Create notification :
- (void)scheduleNotification {

  [[UIApplication sharedApplication] cancelAllLocalNotifications];
 
UILocalNotification notif = [[cls alloc] init];

notif.fireDate = [datePicker date];
notif.timeZone = [NSTimeZone defaultTimeZone];

notif.alertBody = @"Reminder for you";
notif.alertAction = @"Show";
notif.soundName = UILocalNotificationDefaultSoundName;
notif.applicationIconBadgeNumber = 1;

NSDictionary *userDict = [NSDictionary dictionaryWithObject:@"Notification    text" forKey:kRemindMeNotificationDataKey];

notif.userInfo = userDict;

[[UIApplication sharedApplication] scheduleLocalNotification:notif];
[notif release];
}
Cancel any exiting local notification
[[UIApplication sharedApplication] cancelAllLocalNotifications];
Allocate and initialize UILocalNotification object
UILocalNotification *notif = [[cls alloc] init];
Set fire date and timezone. Fire date is date and time when system should deliver the notification. Date is calculated depending on timezone specified.If we do not specify timezone then it will take GMT as default time zone.
 notif.fireDate = [datePicker date]; 

notif.timeZone = [NSTimeZone defaultTimeZone];
We can control alert message displayed when notification is delivered by setting alertBody and alert action by setting alertAction.
notif.alertBody = @"Reminder for you"; 

notif.alertAction = @"Show";
We can also specify sound to be played when notification is delivered by setting soundName and also specify badge number on application icon by setting applicationIconBadgeNumber.
 notif.soundName = UILocalNotificationDefaultSoundName; 

notif.applicationIconBadgeNumber = 1;
We can also pass custom data with notification by adding it into dictionary. We can add dictionary to notification using userInfo property.
NSDictionary *userDict = [NSDictionary dictionaryWithObject:@"Notification text" forKey:kRemindMeNotificationDataKey];

notif.userInfo = userDict;
Here we are passing notification text as custom data.
In case if we want to increase icon badge number we can get current badge number by using.
[[UIApplication sharedApplication] applicationIconBadgeNumber ];
If you want to repeat notification then you can set following property to required calendar unit.
notif.repeatInterval = NSMinuteCalendarUnit;

OR

notif.repeatInterval = NSHourCalendarUnit;

OR

notif.repeatInterval = NSDayCalendarUnit;

OR

notif.repeatInterval = NSWeekCalendarUnit;

App Idea: Are you working on iPhone/iPad app similar to existing one in Store?

Now that there are 300K+ apps on AppStore, there is high possibility that your idea has been implemented and have an app on store for sale.  We are getting many requirements from clients about creating an app similar to one in AppStore and at the same time with the concern, whether they can make money out of it?
It is obvious that existing competition for an app idea means that your life is going to be harder. However, it definitely does not mean that their implementation for the app is the best it could be. If you can add something to the already existing idea that can improve the app or make it more appealing, Go ahead!!
In such scenario, you need smart companies well-versed in market research to figure out whether it would be worth the competition. “We are here for you” :)
Ask yourself these basic questions:
  • Are users who purchased the app happy with the existing app?
  • There are chances in the sea of app world that they are not happy about it , find out the roots.
  • It can be price structure of the app that users are not happy about. Is it wrongly priced? e.g. Unnecessary in-app purchases at regular intervals of app usage, multi-level unlocking of features with payments, prices are not justified for what they offer etc.
  • Can you offer better pricing model?
  • Do you have list of superior features including ‘must-have’?
  • Do you have enough resources and money to compete with existing app?
Lets DISCOVER the potential of your idea together and have a refreshing app experience for 125 Million iOS users.
Team
Mobisoft Infotech

iPhone UITableView Tutorial: Grouped Table

Grouped table view is an extension of the normal table view in iPhone. It displayes the data in several sectioned lists. Each section has a header and number of rows associated with it. Examples of grouped table are the ‘contacts’ list, a dictionary,etc. In this tutorial, we will create a grouped table using a dictionary, to create a names list,unlike the plain table in which we had used an array. So lets get started!
Step 1: Create a view based application and name it ‘GroupedTable’.
Step 2: Put the following code in ‘GroupedTableViewController.h’
#import <UIKit/UIKit.h>

@interface GroupedTableViewController : UIViewController {
 NSDictionary *tableContents;
 NSArray *sortedKeys;
}

@property (nonatomic,retain) NSDictionary *tableContents;
@property (nonatomic,retain) NSArray *sortedKeys;
@end
Here, we have declared a dictionary to hold the section headers and their respective row contents. And an array to hold the sorted keys of the dictionary.
Step 3: Now, open ‘GroupedTableViewController.m’ file and put the following code in it.
#import "GroupedTableViewController.h"

@implementation GroupedTableViewController
@synthesize tableContents;
@synthesize sortedKeys;

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
 NSArray *arrTemp1 = [[NSArray alloc]
                        initWithObjects:@"Andrew",@"Aubrey",@"Alice",nil];
 NSArray *arrTemp2 = [[NSArray alloc]
                        initWithObjects:@"Bob",@"Bill",@"Bianca",nil];
 NSArray *arrTemp3 = [[NSArray alloc]
                        initWithObjects:@"Candice",@"Clint",@"Chris",nil];
 NSDictionary *temp =[[NSDictionary alloc]
               initWithObjectsAndKeys:arrTemp1,@"A",arrTemp2,
                                                       @"B",arrTemp3,@"C",nil];
 self.tableContents =temp;
 [temp release];
 self.sortedKeys =[[self.tableContents allKeys]
                              sortedArrayUsingSelector:@selector(compare:)];
 [arrTemp1 release];
 [arrTemp2 release];
 [arrTemp3 release];
       [super viewDidLoad];
}

- (void)dealloc {
 [tableContents release];
 [sortedKeys release];
        [super dealloc];
}

#pragma mark Table Methods

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return [self.sortedKeys count];
}

- (NSString *)tableView:(UITableView *)tableView
 titleForHeaderInSection:(NSInteger)section
{
 return [self.sortedKeys objectAtIndex:section];
}

- (NSInteger)tableView:(UITableView *)table
numberOfRowsInSection:(NSInteger)section {
 NSArray *listData =[self.tableContents objectForKey:
                                 [self.sortedKeys objectAtIndex:section]];
 return [listData count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView
   cellForRowAtIndexPath:(NSIndexPath *)indexPath {
 static NSString *SimpleTableIdentifier = @"SimpleTableIdentifier";

 NSArray *listData =[self.tableContents objectForKey:
                     [self.sortedKeys objectAtIndex:[indexPath section]]];

 UITableViewCell * cell = [tableView
           dequeueReusableCellWithIdentifier: SimpleTableIdentifier];

 if(cell == nil) {

   cell = [[[UITableViewCell alloc]
   initWithStyle:UITableViewCellStyleDefault
   reuseIdentifier:SimpleTableIdentifier] autorelease];

  /*cell = [[[UITableViewCell alloc]
     initWithStyle:UITableViewCellStyleSubtitle
     reuseIdentifier:SimpleTableIdentifier] autorelease];
  */
 }

 NSUInteger row = [indexPath row];
 cell.textLabel.text = [listData objectAtIndex:row];

 return cell;
}

- (void)tableView:(UITableView *)tableView
didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
 NSArray *listData =[self.tableContents objectForKey:
                    [self.sortedKeys objectAtIndex:[indexPath section]]];
 NSUInteger row = [indexPath row];
 NSString *rowValue = [listData objectAtIndex:row];

 NSString *message = [[NSString alloc] initWithFormat:rowValue];
 UIAlertView *alert = [[UIAlertView alloc]
        initWithTitle:@"You selected"
        message:message delegate:nil
        cancelButtonTitle:@"OK"
        otherButtonTitles:nil];
 [alert show];
 [alert release];
 [message release];
 [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

@end
viewdidLoad: Here, we populate the dictionary using three arrays of names as objects and alphabets as keys. Then we sort the array ‘allKeys’ of the dictionary and put it in sortedKeys.

Table Methods

numberOfSectionsInTableView : Returns the count of keys in the dictionary.
titleForHeaderInSection : Returns the value of key for that particular section.
cellForRowAtIndexPath : Here, listdata is an array which is assigned the value for the key corresponding to the respective section. For every section, the contents of listdata are displayed.
didSelectRowAtIndexPath : In this method, we display an alert view when a row is selected.
Step 4 : Open the ‘GroupedTableViewController.xib’. Drag and drop a table view on it. Select the table view and open its Attributes Inspector (command+1). Change the table style from ‘Plain’ to ‘Grouped’.
Step 5 : Open the Connections Inspector (command+2) for the table and link its datasource and delegate to the file’s owner.

Step 6 : You can download the source code here.Save,build and run the project. The output will be as follows:

iPhone TabBar: UITabBarController Tutorial

A Tab Bar Controller helps to organize an application along functional lines.It is used to switch between multiple pages in an application. Each tab of a tab bar controller interface is associated with a view controller.Whenever a tab is tapped by a user,the tab bar controller object selects the particular tab and displays the corresponding view associated with the tab.This blog will assist you on how to create applications using tab bar controller.
Step 1 : Start Xcode and create a new project by selecting Window- Based Application.
Step 2 : Open “PrjTabBarControllerAppDelegate.h” and put following code in it.
#import <UIKit/UIKit.h>

@interface PrjTabBarControllerAppDelegate:NSObject
<UIApplicationDelegate> {

    UIWindow *window;
    UITabBarController *tcTabBar;
}

@property (nonatomic, retain) IBOutlet UIWindow *window;
@property (nonatomic, retain) IBOutlet *tcTabBar;
@end
Here ‘”tcTabBar” is an instance variable of type UITabBarController. We have created an outlet, so that we can relate our instance ‘tcTabBar’ with TabBarController.
Step 3 : Open “PrjTabBarControllerAppDelegate.m” and put following code in it. In the ‘applicationDidFinishLaunching’ method we have added the Tab Bar Controller as a sub view to the existing window. Save the project using (command + S).
#import "PrjTabBarControllerAppDelegate.h"

@implementation PrjTabBarControllerAppDelegate

@synthesize window;
@synthesize tcTabBar;

- (void)applicationDidFinishLaunching:(UIApplication *)application {

 // Override point for customization after application launch
 [window addSubview:tcTabBar.view];
 [window makeKeyAndVisible];
}

- (void)dealloc {
 [tcTabBar release];
  [window release];
   [super dealloc];
}

@end
Step 4 : Open the Interface Builder by double clicking on MainWindow.xib file. Drag & Drop a Tab Bar Controller from the Library(shift + command + L.). Make sure that the Tab Bar Controller is dropped on the MainWindow.xib since it is not allowed to be placed on the View Controller.We will see a Tab Controller with two bar items created for us. Add one more tab item to it from the library.
As we can see a Tab Bar Item has ‘Title’ & ‘Image’ associated with it. Double Click on Item 1. Open the ‘Attributes Inspector’ (command + 1).In the ‘Atrributes Inspector’ we can set the title & image for Tab Bar Item. The image that we are adding should be present in the Project folder.To add an image to Project right click on ‘Resources’ -> Add -> Existing Files and select the image.
Step 5 : Now connect the Tab Bar Controller to PrjTabBarControllerAppDelegate. Open the ‘Connection Inspector’ (command + 2). Connect “tcTabBar” in the File’s Owner to Tab Bar Controller.
Step 6 : Right click on ‘Classes’ in Group & Files Explorer & add UIViewController subclass file. Select the option ‘With XIB for user interface’. The files added should be equal to number of Tab Bar items present.Here, we add three UIViewController so name them as View1ViewController, View2ViewController, View3ViewController.
Step 7 : Open the View2ViewController.xib by double clicking on it. Set the color of the view from the ‘Attribute Inspector’.Save & Close the .xib file. Similarly set the colours for other views.
Step 8 : Now we need to specify which views should be there in each tab of TabBarController. For this open ‘Interface Builder’. Open ‘Identity Inspector’ (command + 4). Set the class of each Tab Bar Item to its respective view.

Step 9 : Save,Build & Run the project.When we switch the tabs you will observe the views .
You can download the source code here.
Output:

iPhone UIButton tutorial: Radio Buttons

Radio buttons is a set of buttons out of which only one can be set at a time. For example: Selecting the time format out of 12-hr and 24-hr in a clock application.They are often required in iPhone UIs. Unfortunately, they are not included in the iPhone sdk. In this tutorial, we will learn how to create custom radio buttons.
Step 1: Create a window based application in Xcode and name it “MIRadioButtonGroup”.
Step 2: Create new “MIRadioButtonGroup.h” and “MIRadioButtonGroup.m” files which extend from UIView.
(Classes >> Add >> New File >> Objective C Class. Select UIView in the “subclass of” list.)
Step 3: Create a new group in the Classes folder and name it “MIRadioButtonGroup”. Drag the “MIRadioButtonGroup .h” and “MIRadioButtonGroup .m” files into the group.Now, add the images “radio-on.png” and “radio-off.png” to the group.
Step 4: Open the “MIRadioButtonGroup.h” file and make the following changes in it.
@interface MIRadioButtonGroup : UIView {
NSMutableArray *radioButtons;
}

@property (nonatomic,retain) NSMutableArray *radioButtons;

- (id)initWithFrame:(CGRect)frame andOptions:(NSArray *)options
          andColumns:(int)columns;
-(IBAction) radioButtonClicked:(UIButton *) sender;
-(void) removeButtonAtIndex:(int)index;
-(void) setSelected:(int) index;
-(void)clearAll;
@end
Here, we have declared a mutable array “radioButtons” which will hold all the buttons that we add to the radio button group.
The methods declared are:
initWithFrame – It is a constructor used to initialize the group. It takes the frame for the entire group,an array holding the titles of the buttons and the number of columns in which the buttons are to be arranged as input parameters.
radioButtonClicked – This method is used to set the button which is clicked.
removeButtonAtIndex – This method is used to remove a radio button at a particular index from the group.
setSelected – This method is used to set the button at the specified index.
clearAll – This method clears all the buttons including the currently set button.
Step 5: Open the “MIRadioButtonGroup.m” file and put the following code in it.
#import "MIRadioButtonGroup.h"

@implementation MIRadioButtonGroup
@synthesize radioButtons;

- (id)initWithFrame:(CGRect)frame andOptions:(NSArray *)options
      andColumns:(int)columns{

               NSMutableArray *arrTemp =[[NSMutableArray alloc]init];
               self.radioButtons =arrTemp;
               [arrTemp release];
              if (self = [super initWithFrame:frame]) {
                      // Initialization code
                      int framex =0;
                      framex= frame.size.width/columns;
                      int framey = 0;
                      framey =frame.size.height/([options count]/(columns));
                      int rem =[options count]%columns;
                      if(rem !=0){
                             framey =frame.size.height/(([options  count]
                                            /columns)+1);
            }
            int k = 0;
            for(int i=0;i&lt;([options count]/columns);i++){
                 for(int j=0;j<columns;j++){

                          int x = framex*0.25;
                          int y = framey*0.25;
                          UIButton *btTemp = [[UIButton alloc]
                           initWithFrame:CGRectMake(framex*j+x, framey*i+y,
                           framex/2+x, framey/2+y)];
                           [btTemp addTarget:self action:
                           @selector(radioButtonClicked:)
                            forControlEvents:UIControlEventTouchUpInside];
                            btTemp.contentHorizontalAlignment =
                             UIControlContentHorizontalAlignmentLeft;
                           [btTemp setImage:[UIImage imageNamed:
                           @"radio-off.png"] forState:UIControlStateNormal];
                           [btTemp setTitleColor:[UIColor blackColor]
                            forState:UIControlStateNormal];
                           btTemp.titleLabel.font =[UIFont systemFontOfSize:14.f];
                         [btTemp setTitle:[options objectAtIndex:k]
                                 forState:UIControlStateNormal];
                         [self.radioButtons addObject:btTemp];
                         [self addSubview:btTemp];
                         [btTemp release];
                         k++;

               }
        }

        for(int j=0;j<rem;j++){

                int x = framex*0.25;
                int y = framey*0.25;
                UIButton *btTemp = [[UIButton   alloc]
                   initWithFrame:CGRectMake(framex*j+x,
                   framey* ([options count]/columns),
                                                framex/2+x,framey/2+y)];
                [btTemp addTarget:self action:@selector(radioButtonClicked:)
                   forControlEvents:UIControlEventTouchUpInside];
                btTemp.contentHorizontalAlignment =
                     UIControlContentHorizontalAlignmentLeft;
               [btTemp setImage:[UIImage imageNamed:@"radio-off.png"]
                                  forState:UIControlStateNormal];
               [btTemp setTitleColor:[UIColor blackColor]
                                    forState:UIControlStateNormal];
               btTemp.titleLabel.font =[UIFont systemFontOfSize:14.f];
               [btTemp setTitle:[options objectAtIndex:k]
                                        forState:UIControlStateNormal];
               [self.radioButtons addObject:btTemp];
               [self addSubview:btTemp];
               [btTemp release];
               k++;

        }

    }
       return self;
}

- (void)dealloc {
         [radioButtons release];
         [super dealloc];
}

-(IBAction) radioButtonClicked:(UIButton *) sender{

           for(int i=0;i&lt;[self.radioButtons count];i++){
                   [[self.radioButtons objectAtIndex:i] setImage:[UIImage
                               imageNamed:@"radio-off.png"]
                                    forState:UIControlStateNormal];
           }
           [sender setImage:[UIImage imageNamed:@"radio-on.png"]
                                 forState:UIControlStateNormal];

}

-(void) removeButtonAtIndex:(int)index{
           [[self.radioButtons objectAtIndex:index] removeFromSuperview];
}

-(void) setSelected:(int) index{
        for(int i=0;i&lt;[self.radioButtons count];i++){
             [[self.radioButtons objectAtIndex:i] setImage:[UIImage
           imageNamed:@"radio-off.png"] forState:UIControlStateNormal];

         }
         [[self.radioButtons objectAtIndex:index] setImage:[UIImage
          imageNamed:@"radio-on.png"] forState:UIControlStateNormal];

}

-(void)clearAll{
          for(int i=0;i&lt;[self.radioButtons count];i++){
                     [[self.radioButtons objectAtIndex:i] setImage:[UIImage
                                                 imageNamed:@"radio-off.png"]
                                                 forState:UIControlStateNormal];
            }
}

@end
initWithFrame – In this method, we first divide the frame into n number of boxes with width framex and height framey, where n =([options count]/columns)*columns. Then we check to see if there is any remainder for ([options count]/columns). The reason for this will be explained later.
In the proceeding nested “for” loops, we set the frames of the buttons so that each button occupies 50% space of each of the n boxes. After that we link the button programmatically to the “radioButtonClicked” method. We set the alignment of the content(radio button image and title) to left. Then we set the image for the button, configure its font color and font size and set its title.
This code works fine when the number of buttons is perfectly divisible by columns, but when it is not, the remaining buttons are not printed.
Now, the remainder comes in picture. What we do is, if there is a non-zero remainder, we add 1 to the divisor in framey equation,so that there is space for an extra row in the frame. In the next “for” loop, we insert that extra row and hence, cover the missing buttons.
radioButtonClicked – Here, we first clear all the buttons in the “radioButtons” array by setting their images to “radio-off.png”. Then, we set only the sender button by setting its image to “radio-off”.
removeButtonAtIndex – In this method, we remove the button at the specified index with the “removeFromSuperview” method.
setSelected – This method is similar to the “radioButtonClicked” method. The difference is we set the button at the specified index in the “radioButtons” array.
clearAll – In this method, we clear all the radio buttons by setting the images of the buttons in “radioButton” to “radio-off.png”.
Step 6: Now that we have created the “MIRadioButtonGroup” files, put the following code in the “MIRadioButtonGroupAppDelegate.m” file so that we can test them.
#import "MIRadioButtonGroupAppDelegate.h"
#import "MIRadioButtonGroup.h"

@implementation MIRadioButtonGroupAppDelegate
@synthesize window;

- (void)applicationDidFinishLaunching:(UIApplication *)application {

         // Override point for customization after application launch
         NSArray *options =[[NSArray alloc]
                        initWithObjects:@"1",@"2",@"3",@"4",@"5",@"6",nil];
         MIRadioButtonGroup *group =[[MIRadioButtonGroup alloc]
                                   initWithFrame:CGRectMake(0, 20, 320, 75)
                                             andOptions:options andColumns:4];
          [options release];
          [window addSubview:group];
          //[group setSelected:1];
         //[group clearAll];
        //[group removeButtonAtIndex:2];
        [window makeKeyAndVisible];
}

- (void)dealloc {
         [window release];
         [super dealloc];
}

@end
Step 7: Save, build and run the project. The output will be Output1. Now uncomment the commented lines one by one and observe the output. It will be Output 2, Output 3 and Output 1 respectively.
You can download the source code here.

iPhone UIButton tutorial : Custom Checkboxes

Checkbox is one of the elements that is frequently required in iPhone UIs, but the traditional checkbox is not present in iPhone sdk. Switches are sometimes used in the place of checkboxes.
In this tutorial, we will see how to create a custom checkbox. It extends from UIButton class. It is used to select or deselect a particular item or more than one items in a list. For example: The “Keep me signed in” checkbox in certain apps, sound on/off , effects on/off checkboxes in Settings of a gaming app.If more checkboxes are needed, we can create them similarly.
Step 1: Create a window based application in Xcode and name it “MICheckBox”.
Step 2: Create new “MICheckBox.h” and “MICheckBox.m” files which extend from UIView.
(Classes >> Add >> New File >> Objective C Class. Select UIView in the “subclass of” list.)
Step 3: Create a new group in the Classes folder and name it “MICheckBoxUtils”. Drag the “MICheckBox.h” and “MICheckBox.m” files into the group.Now, add the images “checkbox_not_ticked.png” and “checkbox_ticked.png” to the group.
Step 4: Open the “MICheckBox.h” file and make the following changes in it.
@interface MICheckBox : UIButton {
       BOOL isChecked;
}
@property (nonatomic,assign) BOOL isChecked;
-(IBAction) checkBoxClicked;
Here, we have changed the UIView class from which it extends to UIButton. Also, we have declared a boolean property “isChecked” which
keeps a track of whether the button is checked or not. “checkBoxClicked” is the method to change the state of checkbox when it is clicked.
Step 5: Now, open the “MICheckBox.m” file and add the following code to it.
#import "MICheckBox.h"

@implementation MICheckBox
@synthesize isChecked;

- (id)initWithFrame:(CGRect)frame {
              if (self = [super initWithFrame:frame]) {
                         // Initialization code

                         self.contentHorizontalAlignment =
                                    UIControlContentHorizontalAlignmentLeft;

                         [self setImage:[UIImage imageNamed:
                                     @"checkbox_not_ticked.png"]
                                     forState:UIControlStateNormal];

                          [self addTarget:self action:
                                     @selector(checkBoxClicked)
                              forControlEvents:UIControlEventTouchUpInside];
                }
                return self;
}

-(IBAction) checkBoxClicked{
               if(self.isChecked ==NO){
                        self.isChecked =YES;
                       [self setImage:[UIImage imageNamed:
                                    @"checkbox_ticked.png"]
                                    forState:UIControlStateNormal];

                }else{
                        self.isChecked =NO;
                        [self setImage:[UIImage imageNamed:
                                         @"checkbox_not_ticked.png"]
                                         forState:UIControlStateNormal];

                }
}

- (void)dealloc {
             [super dealloc];
}

@end
initWithFrame” method – This method initializes the button with the frame given by us. The contentHorizontalAlignment property allows us to set the alignment of the content (i.e image and text) of the button(checkbox). Initially, the image of the button will be the unselected checkbox, so we set the image “checkbox_not_ticked.png”. Then we programmatically link the button to the “checkBoxClicked” method.
“checkBoxClicked” method – In this method, whenever the checkbox is clicked, the image is changed from checked to unchecked and vice versa.
Step 6: Now that we have created the “MICheckBox” files, we need to test them. Hence, put the following code in the “MICheckBoxAppDelegate.m” file.
#import "MICheckBoxAppDelegate.h"
#import "MICheckBox.h"

@implementation MICheckBoxAppDelegate
@synthesize window;

- (void)applicationDidFinishLaunching:(UIApplication *)application {

             // Override point for customization after application launch
             MICheckBox *checkBox =[[MICheckBox alloc]
                          initWithFrame:CGRectMake(100, 200, 150, 25)];

             [checkBox setTitleColor:[UIColor blackColor]
                          forState:UIControlStateNormal];

             [checkBox setTitle:@"Checkbox"
                          forState:UIControlStateNormal];

             [window addSubview:checkBox];
             [window makeKeyAndVisible];
}

- (void)dealloc {
                 [window release];
                 [super dealloc];
}

@end
Here, we have imported the “MICheckBox.h” file so that we can create its instance. In the “applicationDidFinishLaunching” method, we create an object of MICheckbox and set its title color to black. Also, we set its title to CheckBox. Then we add the checkbox to the main window by the “addSubview” method.
Step 7: Download the source code for this tutorial here.
The output will be as follows:
CheckBox Unticked
CheckBox Ticked