首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >传递值作为Kotlin中的参考

传递值作为Kotlin中的参考
EN

Stack Overflow用户
提问于 2022-03-30 04:43:04
回答 2查看 148关注 0票数 0

我想把代码目标C转换成Kotlin多平台这是目标C代码

代码语言:javascript
复制
{
    NSFileManager *fileManager = [[NSFileManager alloc] init];

    BOOL isDir;
    BOOL exists = [fileManager fileExistsAtPath:path isDirectory:&isDir];
    BOOL success = false;

    if (isDir && exists) {
        NSURL *pathUrl = [NSURL fileURLWithPath:path];
        NSError *error = nil;
        success = [pathUrl setResourceValue:isExcluded
                                     forKey:NSURLIsExcludedFromBackupKey
                                      error:&error];

        if (!success) {
            NSLog(@"Could not exclude AsyncStorage dir from backup %@", error);
        }
    }
    return success;
}

在上面的代码变量中,isDir使用&当传递到函数fileExistsAtPath时,我如何在Kotlin中这样使用isDir。我知道这是address-of unary operator

我能用一下吗

代码语言:javascript
复制
  val isDir: CPointer<BooleanVar /* = kotlinx.cinterop.BooleanVarOf<kotlin.Boolean> */>? = null
        val exists = fileManager?.fileExistsAtPath(path, isDir)
EN

Stack Overflow用户

回答已采纳

发布于 2022-03-30 05:30:58

要在Kotlin中创建指针,需要memScoped,在此范围内可以调用alloc来创建任意类型的指针。

下面是如何用Kotlin编写代码:

代码语言:javascript
复制
return memScoped {
    val fileManager = NSFileManager.defaultManager
    val isDir = alloc<BooleanVar>()
    val exists = fileManager.fileExistsAtPath(path, isDirectory = isDir.ptr)
    var success = false
    if (exists && isDir.value) {
        val pathUrl = NSURL.fileURLWithPath(path)
        val error = alloc<ObjCObjectVar<NSError?>>()
        success = pathUrl.setResourceValue(isExcluded, forKey = NSURLIsExcludedFromBackupKey, error = error.ptr)
        if (!success) {
            println("Could not exclude AsyncStorage dir from backup ${error.value}")
        }
    }
    return@memScoped success
}
票数 4
EN
查看全部 2 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71671601

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档