gpt4 book ai didi

ios - Swift 和 Objective-C 无法分配全局变量

转载 作者:行者123 更新时间:2023-11-30 12:09:19 26 4
gpt4 key购买 nike

作为 Swift 初学者,我正在使用 Swift 构建一个应用程序。

在 TestOC2Swft.swift 中,我创建一个名为 macStr 的全局变量:

var macStr:String?

我有一个函数(Func 1)来为其赋值:

func changeWindVol(inputStr:NSString){
macStr=inputStr as String
}

我还有另一个函数(Func 2)来获取这个字符串,例如:

@IBAction func TestBtn(_ sender: Any) {
print(macStr! as String)
}

字符串 inputStr 来自第 3 方 Objective-C 文件:

TestOC2Swft *testSw = [[TestOC2Swft alloc]init];
[testSw changeWindVolWithInputStr:dev.mac];

然后我运行调试模块:

在 Func 1 之前,macStr 为 nil。

功能 1 之后: after func 1

我们可以看到 macStr 被正确分配。然而,在 Func 2 中: capture at func 2 .

macStr的值又变成nil了!

最后会出现一些很长很长的错误信息:

    libswiftCore.dylib`function signature specialization <preserving fragile attribute, Arg[2] = Dead, Arg[3] = Dead> of Swift._fatalErrorMessage (Swift.StaticString, Swift.StaticString, file : Swift.StaticString, line : Swift.UInt, flags : Swift.UInt32) -> Swift.Never:
...
Swift.StaticString, line : Swift.UInt, flags : Swift.UInt32) -> Swift.Never).(closure #2)
...
0x100400444 <+116>: bl 0x1002e14dc ; function signature specialization <preserving fragile attribute, Arg[1] = [Closure Propagated : reabstraction thunk helper from @callee_owned (@unowned Swift.UnsafeBufferPointer<Swift.UInt8>) -> () to @callee_owned (@unowned Swift.UnsafeBufferPointer<Swift.UInt8>) -> (@out ()), Argument Types : [@callee_owned (@unowned Swift.UnsafeBufferPointer<Swift.UInt8>) -> ()]> of generic specialization <preserving fragile attribute, ()> of Swift.StaticString.withUTF8Buffer <A> ((Swift.UnsafeBufferPointer<Swift.UInt8>) -> A) -> A
-> 0x100400448 <+120>: brk #0x1

我完全无法理解这个错误消息。

我那可怜的应用程序出了什么问题?如何更改全局变量 macStr?

最佳答案

我认为您会从这里的单例模式中受益。在单独的 Swift 文件中:

class GlobalVariables {
static var macStr: String?
}

然后在函数1中:

func changeWindVol(inputStr:NSString){
GlobalVariables.macStr = inputStr as String
}

在函数 2 中:

@IBAction func TestBtn(_ sender: Any) {
guard let macStr = GlobalVariables.macStr else { return }
print(macStr)
}

关于ios - Swift 和 Objective-C 无法分配全局变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46264725/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com