可以使用objective c指针指向swift对象实例

时间:2016-04-21 17:43:47

标签: objective-c swift pointers object

这可能是一个愚蠢的问题,但我有一个类我在swift重写,我正在尝试分配一个目标c类中的指针。这是可能的,对吗?

我还没有转换其他课程的原因是我正在尝试将课程转换为分餐。

1 个答案:

答案 0 :(得分:0)

请看这里:

https://developer.apple.com/library/ios/documentation/Swift/Conceptual/BuildingCocoaApps/

特别是本节:

https://developer.apple.com/library/ios/documentation/Swift/Conceptual/BuildingCocoaApps/MixandMatch.html#//apple_ref/doc/uid/TP40014216-CH10-ID122

这是一个简单的例子:

// A Swift class to be used in Objective C
// Note: it must inherit from NSObject, whether directly or not!
class SwiftClass : NSObject
{
    var i : Int32 = 333;

    // This function will be called from Objective C and passed a pointer to a 
    // SwiftClass instance allocated in Objective C.
    static func printSwiftClass( sc : SwiftClass)
    {
        print("The value of property i is \(sc.i)")
    }
}

// Call an Objective-C function that will use a pointer to SwiftClass
ClassObjC.staticFun()

// This goes into the bridging header, directly or indirectly.
// Needed to let Swift know about the ClassObjC class and its
// interface
@interface ClassObjC : NSObject

+(void)staticFun;

@end

这是Objective-C类的实现:

// This header is auto-generated by Xcode and has Swift definitions
// for use in Objective C
#import "cli_swift-Swift.h"

@implementation ClassObjC

+(void)staticFun
{
    // Create a SwiftClass instance
    SwiftClass *sc = [[SwiftClass alloc] init];
    // Set its i property
    sc.i = 444;
    // Call a Swift function to print the property i of the SwiftClass
    // instance we just created
    [SwiftClass printSwiftClass:sc];
}

@end