我想將代碼 Objective C 轉換為 Kotlin 多平臺 這是 Objective C 代碼
{
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
我怎么能isDir像在 Kotlin 中那樣使用。我知道這是
一元運算子的地址
我可以用嗎
val isDir: CPointer<BooleanVar /* = kotlinx.cinterop.BooleanVarOf<kotlin.Boolean> */>? = null
val exists = fileManager?.fileExistsAtPath(path, isDir)
uj5u.com熱心網友回復:
要在 Kotlin 中創建指標,您需要memScoped在此范圍內呼叫alloc以創建任何型別的指標。
以下是您可以使用 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
}
uj5u.com熱心網友回復:
您可以傳遞 lambda 并更改其中的 bool 值
var isDir: Boolean = false
fileExistsAtPath(onChange = { newValue -> isDir = newValue })
但我認為這不是一個好方法。嘗試data class使用 2 個欄位創建:isDir和exists,或Pair至少使用。并從函式中回傳它們fileExistsAtPath
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/452650.html
標籤:安卓 IOS 目标-c 科特林 kotlin-多平台
上一篇:在Swift中合并子陣列
