Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to implement Objective C code in swift project?

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 1
    • 0
    • 542
    Comment on it

    Let's suppose we have one project in Swift and we want to include .m file of Obj C in our project, for that we have to follow below steps.


    1. Drag your objective C .m file  in swift project. Once you drag, you will get one pop up as shown below. Click on yes.

     

    2. If you accidentally clicked on "No" then you can manually create a header file named "<AppName>-Bridging-Header.h" form File -> New -> File and selecting "header file".

    Now go to Build Setting option in your project and in search write Objective-C Bridging Header. Double click on the right side of Objective-C Bridging Header option and you will get a text area.

    Drag your new created bridging header h file and drop it in that text area.


    3. Now add objective c .h file also i.e “DemoObject.h”

     

    4. In DemoObject.h add some property and then your .h file will look like this.

    #import <Foundation/Foundation.h>
    
    @interface DemoObject : NSObject
    
    @property (strong, nonatomic) id someProperty;
    
    - (void) someMethod;
    
    @end
    

     

    5. In DemoObject.m implement below code.

    #import "DemoObject.h"
    
    @implementation DemoObject 
    
    - (void) someMethod {
        NSLog(@"method of Objective c file");
    }
    
    @end

     

    6. Now in your bridging header file import the DemoObject.h file in this way : #import "DemoObject.h"

     

    7. As you want to implement this Objective C code in swift so make one swift file in your project lets give name “DemoSwiftViewController.swift”

     

    8. Implement below code in view did load method of DemoSwiftViewController and now you can run this code.

    var instanceOfDemoObject: DemoObject = DemoObject()
    instanceOfDemoObject.someProperty = "Hello World"
    print(instanceOfDemoObject.someProperty)
    instanceOfDemoObject.someMethod()

     

    In this way you can add objective c file in swift project. if you have any questions please feel free to ask in comments section

    How to implement Objective C code in swift project?

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: