Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing Objective-c base class's instance variables from a Swift class

Having an Objective c base class:

@interface ObjcClass : NSObject {
    NSString *aVariable_;
}

And a swift sub-class:

class SwiftClass : ObjcClass {
    func init() {
        // aVariable_ can't be accessed here. An Objective-c derived
        // class has direct access to it's super's instance variables!
    }
}

How do I access ObjcClass aVariable_ from within SwiftClass?

like image 774
Shai Avatar asked Sep 28 '14 08:09

Shai


People also ask

Can Objective-C class inherit from Swift class?

Unfortunately, it's not possible to subclass a Swift class in Objective-C. Straight from the docs: You cannot subclass a Swift class in Objective-C.

How do you declare an instance variable in Objective-C?

Objective-C is more like C/C++ than Java. Java is relatively unique in that it doesn't have separate declaration and implementation files but puts everything in one file. In Objective-C you declare the instance fields in the @interface section of your . h file.

What is instance variable in Swift?

In addition to properties, you can use instance variables as a backing store for the values stored in a property. Swift unifies these concepts into a single property declaration. A Swift property doesn't have a corresponding instance variable, and the backing store for a property isn't accessed directly.


3 Answers

Great query. We have tried to hard to get this done. The only working solution I found

get value by using self.valueForKey("aVariable_")

set value using self.setValue("New Value", forKey: "aVariable_")

Hope that helps. Possible solution without altering super class.

like image 82
Narendra Avatar answered Oct 17 '22 01:10

Narendra


I couldn't find a "proper" way to do this, but I needed badly for it to work. My solution was to create a simple getter method in my Objective C superclass, like this:

header file

@interface ObjcClass : NSObject {
    NSString *myVariable;
}
- (NSString *)myVariable;


in the implementation file

- (NSString *)myVariable {
    return myVariable;
}

I'd love to hear of a better way of doing it, but this at least works.

like image 6
Casey Perkins Avatar answered Oct 17 '22 01:10

Casey Perkins


I've searched a lot for this. Eventually I changed my code from:

@interface PrjRec : NSObject {
    @public
    NSString* name;
}
@end

To:

@interface PrjRec : NSObject {
}

@property NSString* name;

@end

similar to @JasonTyler solution. Then I can access to my object property from Swift code with simple dot notation <object instance>.name,

But I needed to change all existing objective-c references from

<object instance>->name

To:

<object instance>.name

or

_name

if inside class unit.

I hope for a better solution too.

like image 4
Giorgio Calzolato Avatar answered Oct 17 '22 01:10

Giorgio Calzolato