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
?
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.
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With