Accessing Objective-C Base Class's Instance Variables from a Swift Class

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

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.

Objective-c, how to access an instance variable from another class

A public class variable in Java is equivalent to a global variable in C and Objective-C. You would implement it as:

class1.h

extern NSString* MyGlobalPassword;

class1.m

NSString* MyGlobalPassword = nil;

Then, anyone that imports class1.h can read and write to MyGlobalPassword.

A slightly better approach would be make it accessible via a "class method".

class1.h:

@interface Class1 : UIViewController {
UITextField *usernameField;
UITextField *passwordField;
UIButton *loginButton;
}
+ (NSString*)password;
@end

class1.m:

static NSString* myStaticPassword = nil;

@implementation Class1
+ (NSString*)password {
return myStaticPassword;
}

- (void)didClickLoginButton:(id)sender {
[myStaticPassword release];
myStaticPassword = [passwordField.text retain];
}

Other classes would then read the password through the password class method.

Class2.m :

-(void) someMethodUsingPassword {
thePassword = [Class1 password]; // This is how to call a Class Method in Objective C
NSLog(@"The password is: %@", thePassword);
}

Using Swift Shared Instance in Objective C

There's nothing wrong with your Swift, or with how you access the singleton instance from ObjC — the problem is the enum value you're passing to it.

Presumably your enum declaration looks something like this:

enum PlayerAction: Int {
case Stop, Collaborate, Listen // etc
}

To make your enum accessible to ObjC, you need to preface the declaration with @objc:

@objc enum PlayerAction: Int { /*...*/ }

This makes it appear as a Cocoa-style NS_ENUM declaration in ObjC, creating global symbols for case names by concatenating the Swift enum type's name with the case names:

typedef NS_ENUM(NSInteger, PlayerAction) {
PlayerActionStop = 1,
PlayerActionCollaborate,
PlayerActionListen, // etc
};

So those names are what you should be passing when you call a method taking an enum value from ObjC:

[signaler firePlayerAction: PlayerActionStop]; // NOT PlayerAction.Stop

(The only docs I can find to cite for this are buried in the Attributes chapter in The Swift Programming Language — scroll down the to objc attribute.)



Related Topics



Leave a reply



Submit