I was exploring the NSObject documentation for Swift and I was surprised to see
that alloc is callable in Swift.
I was even more surprised when I did some tests to see how it functions.
Here’s some code, taken from a Playground:
import Cocoa
class SomeClass: NSObject {
override class func alloc() -> SomeClass {
println("I'm alloc-ing!")
return super.alloc() as! SomeClass
}
var someInt: Int
override init () {
someInt = 5
super.init()
println("I'm initing!")
}
}
println("** Checkpoint 1 **")
let x = SomeClass.alloc()
println("** Checkpoint 2 **")
let y = SomeClass()
println("** Checkpoint 3 **")
SomeClass.`new`()
What this code shows you when you run it is that:
1) You can use alloc to create an object that completely bypasses your Swift
initializer(s), and which has garbage (zero) values for all of its properties.
You can do this whether or not you override alloc. Once created, it does not
appear that there is any way to run an initializer on this object.
2) If you override alloc and you do use your Swift initializer, your override
of alloc is *not* called.
3) If you use `new`, then both alloc and your Swift initializer are called.
What I would expect:
A) Swift would not expose alloc or `new` at all. There shouldn’t be a way to
create objects without going through an initializer.
B) If a class does override alloc (either in Swift in or a mixed Objective-C /
Swift project), then initializing an object would call the overridden alloc
method.
C) That in Swift, the NSObject alloc method would be “final” so that it
couldn’t be overridden.
From this, I have two questions:
First, what is the purpose of exposing alloc and `new` in Swift? It seems like
a great way for people to get in trouble and/or develop bad habits.
Second, is the behavior of bypassing an alloc override expected when using a
Swift initializer on a class that inherits from NSObject?
Thanks for any insight that you can give me on this. I’ve also filed Radars
19830482, 19830571 and 19830767.
Sincerely,
Michael Patrick Ellard
_______________________________________________
Do not post admin requests to the list. They will be ignored.
Xcode-users mailing list ([email protected])
Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/xcode-users/archive%40mail-archive.com
This email sent to [email protected]