1.我有一个swift项目,在XMPP注册模块,我使用闭包传值(代理会了,学学闭包用法),把注册结果传回控制器。
1 初始化
2注册成功赋值
3 作为返回值
4 在控制器中调用
5 结果是不注册他直接不注册,也不连接服务器了。直接返回
6 然后 我找到一个解决办法,一开始给上一种注册结果
7 再 返回
8 最后 结果出来了 注册成功
但是 把我给他初始化赋的结果也打印出来了
咋回事啊 ?
大家讲道理2017-04-17 17:50:47
I see that this of yours has nothing to do with closure Closure
Closure
并没有关系
以下解答
此次 Crash 的问题很明显, 你对一个值为 nil
的 Optional
类型进行了强制解包
图5:'fatal error: unexpectedly found nil while unwrapping an optional value'
原因
你的 connectToHost()
应该是异步方法. 该行执行后, 立即就执行了 return registerRes!
但此时, 你的连接还进行中还未回调 func xmppStreamDidRegister(sender: XMPPStream!)
方法
你的 registerRes
还是初始化的时候的值 nil
The following answer
The problem with this crash is obvious, you forced a Optional
type with a value of nil
Unpack
🎜Figure 5: 'fatal error: unexpectedly found nil while unwrapping an optional value'🎜Reason
connectToHost()
should be an asynchronous method. After this line is executed, return registerRes!
func xmppStreamDidRegister(sender: XMPPStream!)
method has not been called back yetregisterRes
is still the value nil
when initialized巴扎黑2017-04-17 17:50:47
Your whole process has nothing to do with closures... Since your variable will definitely have a value, you can actually use an exclamation mark instead of a question mark, so you don't need to assign nil to it when creating it, and you don't need to manually unpack it when getting it. Well, I'm just talking about a small problem in your code. As for the reason for the question you want to ask, it has been mentioned above. You can create a callback and hang this callback on connectHost. It's just that this will open a hole in each layer to pass the callback... Of course, there are elegant solutions. There is a project on Github called Async that you can refer to, because I haven't looked at its implementation carefully and it's hard to show off here.