Sunday, August 5, 2012

Cocoa: Creating your own frameworks

This tutorial is about reusing your code by means of a framework. In this tutorial, we are going to learn, how to create frameworks in cocoa using Xcode and how can we use these frameworks in our applications.

All you need to know before going through this post is just the basic knowledge of objective - C and Xcode.

So, lets begin.

Creating a Framework

  1. Create a new project in Xcode using the Cocoa Framework template.


  2. Create a class which will contain your implementation

  3. Implement your methods in the yourClass.m file and declare them as well in the yourClass.h file as shown below:

    TestClass.h
    #import <Cocoa/Cocoa.h>

    @interface TestClass : NSObject
    +(void)showMessage;
    @end

    TestClass.m
    #import "TestClass.h"

    @implementation TestClass
    +(void)showMessage
    {
        NSLog(@"This is the MESSAGE");
    }
    @end

  4. To make the headers of yourClass available to the application developer, you need to mark the yourClass.h  file as public (which is specified as project by default) as shown in image below:

  5. Now, you need to set the Installation Directory  for your framework ( you can set it to any location you please but I prefer @executable_path/../Frameworks )

  6. Build your framework and you are good to go.

Using your framework in an Application

Now, lets see how we can use our framework in an application. For this purpose we will create a sample test application.

  1. Create an application using the cocoa application  template.

  2. Add the framework you just created in your application.

  3. Add a new Copy Files build phase.



  4. Use your framework's classes like any other class as shown below:

    AppDelegate.h
    #import <Cocoa/Cocoa.h>

    @interface AppDelegate : NSObject <NSApplicationDelegate>

    @property (assign) IBOutlet NSWindow *window;

    @end

    AppDelegate.m
    #import "AppDelegate.h"
    #import "TestFramework/TestClass.h"

    @implementation AppDelegate
    @synthesize window = _window;
    - (void)dealloc
    {
        [super dealloc];
    }

    - (void)applicationDidFinishLaunching:(NSNotification *)aNotification
    {
        // Insert code here to initialize your application
        [TestClass showMessage];
    }

    @end


    And VOILA......


Please do leave your comments behind.

No comments:

Post a Comment