简体   繁体   中英

access objective-c variable in swift

Hi guys I have two view controllers in my storyboard, a tableViewController and a Normal ViewController. A button in the tableViewController(Not in a cell) segues to the second view. However the tableViewController has an objective-c class which I didn't write by myself.

// When data is comming, this will be called
- (void)bleDidReceiveData:(unsigned char *)data length:(int)length {
    NSData *d = [NSData dataWithBytes:data length:length];
    NSString *s = [[NSString alloc] initWithData:d encoding:NSUTF8StringEncoding];
    NSLog(@"received data: %@", s);   
}

I want to access a "s" from the second view controller which is in swift.

Example:

var data : NSString = s

The way the OC method is written, s only exists inside that method. If you want to get it from code in a different class, it needs to be publicly accessible.

The simplest way is to change from using a local variable to using a property for storing the string.

Here is how to do it based on my understanding.

On Objective-C class .h (header)

@class yourObjectiveCClass
@interface yourObjectiveCClass {
NSString *s;
}
@property (nonatomic, nullable) NSString *s;
@end

An then, on the Objective-C class .m

@interface yourObjectiveCClass ()
...
@end

@implementation yourObjectiveCClass
@synthesize *s;
@end

Now you can access string s from the Swift file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM