Search code examples
androidiosobjective-ckotlinkotlin-multiplatform

Pass value as reference in Kotlin


I want to convert code Objective C to Kotlin multiplatform This is Objective C code

{
    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;
}

In above code variable isDir use & when pass to function fileExistsAtPath So how can I use isDir like that in Kotlin. I know this is address-of unary operator

Can I use

  val isDir: CPointer<BooleanVar /* = kotlinx.cinterop.BooleanVarOf<kotlin.Boolean> */>? = null
        val exists = fileManager?.fileExistsAtPath(path, isDir)

Solution

  • To create a pointer in Kotlin, you need memScoped, inside this scope you can call alloc to create a pointer of any type.

    Here's how you code can be written in Kotlin:

    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
    }