Tuesday, September 30, 2014

Swift - Calling Objective-C code

In Xcode 6, you now have the option to create a project using either Swift or Objective-C. In addition, you can also use Objective-C code in your Swift project. This post shows you how. 

1. First, create an iOS project that uses the Swift language

2. Add a Objective-C File file to your project. Name it as MyClass

3. You will be prompted with the following:


4. This will add a file named UsingObjC-Bridging-Header.h to your project. Behind the scene, Xcode automatically sets the Objective-C Bridging Header setting to this file:


5. Add a Header File file to your project. Name it as MyClass

6. Populate the MyClass.h with the following:

#import

@interface MyClass: NSObject

@property (strong, nonatomic) NSString *property;

- (void) method;

@end

7. Populate the MyClass.m with the following:

#import "MyClass.h"

@implementation MyClass

- (void) method {
    NSLog(@"In method now");
}

@end

8. Populate the UsingObjC-Bridging-Header.h with the following:

#import "MyClass.h"

9. To use the Objective-C class that you have added to your project, add the following statements in bold to the ViewController.swift file:

    override func viewDidLoad() {
        super.viewDidLoad()

        // create an instance of the class
        var myClass: MyClass = MyClass()

        // set its property
        myClass.property = "some random strings here"

        // call its method
        myClass.method()
        
        // retrieve its property
        println(myClass.property)

    }

No comments: