objective-c - 使用 **void 参数从 swift 访问 objective-c 函数

标签 objective-c swift

这主要是一个“学术”问题,所以请不要问“你为什么需要这样做”:-)

我有这个 objective-c 方法,我没有使用 ARC(我知道如果我不释放分配的字符串它会泄漏)。 此方法采用指向内存中某物的指针,然后将指向的内容更改为 NSMutableString。

+(void) writeString:(void **)var
{
    NSMutableString *aString = [[NSMutableString alloc] initWithFormat:@"pippo %@", @"pluto"];
    *var = aString;
}

在 Objective C 中,我以这种方式访问​​它并且它工作正常

NSString *str;
[FLSwiftUtils writeString:&str];
NSLog(@"%@", str);  // prints pippo pluto

现在我想以同样的方式从 Swift 访问它,但我对指针有疑问。 我试过这种方式:

    var opaque = COpaquePointer.null()   // create a new opaque pointer pointing to null
    FLSwiftUtils.writeString(&opaque)
    println(opaque)

但它打印 VSs14COpaquePointer(有 1 个 child ),因为 opaque 是一个指针,我不明白如何推导它并访问指向的 NSMutableString

如果我尝试从不透明值开始创建一个 UnsafePointer:

    var str = UnsafePointer<NSMutableString>(opaque)
    println(str)

println 打印一个空行

我什至试过这个:

    var secondStr = AutoreleasingUnsafePointer<NSMutableString>(opaque.value)
    println(secondStr)
    println(secondStr.memory)

但它打印

VSs26AutoreleasingUnsafePointer(有 1 个 child ) __NSCF字符串

我想我已经接近解决方案了,但我肯定做错了什么。

最佳答案

我在 Apple 论坛上收到了答案(注意:此代码是 FOR ARC)

+ (void)writeString:(void **)var
{
    NSMutableString *aString = [[NSMutableString alloc] initWithFormat:@"pippo %@", @"pluto"];  // this is autoreleased by ARC

    *var = (void *)CFBridgingRetain(aString);   // send a retain, the release will be sent at the swift side
}

然后像这样将它发布到 Swift 中:

    var opaque = COpaquePointer.null()   // create a new opaque pointer pointing to null
    TestClass.writeString(&opaque)

    var string = Unmanaged<NSString>.fromOpaque(opaque).takeRetainedValue()  // this function: creates an object, from the opaque pointer "opaque", take it's value and balance it with a release
    println(string)

关于objective-c - 使用 **void 参数从 swift 访问 objective-c 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24080991/

相关文章:

ios - 如何在不打开 MailComposer 或 objective-c 中的新 View 的情况下通过代码发送邮件

c - 如何@synthesize C 风格的指针数组?

objective-c - 使用 GDB 调试器按对象 ID(即 0xee63d60)打印对象

swift - UICollectionView 未在 UITableViewCell 内部更新

ios - UIKeyboardDidShow 触发太频繁?

ios - Swift 单元测试无法识别新的类初始值设定项

objective-c - iOS 从字符串获取 NSDate?

ios - 将 UITableView 滚动手势传递给 superview UITableView

ios - 如何在 Swift SpriteKit 中集成 Chartboost SDK?

ios - 如何修复 swift 4 中的 UITableView 单元格重复