-1

Can someone please explain how certain functions get called? Is a function named as init going to be called automatically when someone creates a new object like so: var object: type = type(param1). I have also seen this in NSURLConnection. Methods seem to have names like connectionDidFinishLoading or something but I don't understand, is it coded into the swift language for that name to have special actions? Is that function just gonna run as soon the connection finished? Like how would it even know unless you "sent a message" to that function.

4

1 回答 1

0

好的,首先,在 Swift 中,您不再向对象“发送消息”。函数和方法调用由编译器直接链接在一起。唯一的例外是当您拥有继承自的对象时,NSObject因为它仍然在 Objective-C 运行时上运行。

其次,type(param1)是一个init函数的例子。它不是“自动”调用它。这就是在 Swift 中定义初始化方法的方式。您在创建对象时直接调用它。

第三connectionDidFinishLoading是定义在NSURLConnectionDataDelegate. 当你创建一个NSURLConnection你可以给它一个应该实现这个协议的委托。如果您将对象设置为实现协议的委托,则NSURLConnection实例将在适当时调用该方法。这就是整个 UIKit 和 Cocoa 中的委托模式的工作原理。

于 2014-06-27T05:58:50.080 回答