Centurion
Centurion

Reputation: 14314

How to override and use alloc in Swift?

How to override object creation (alloc) and to add a custom logic? The reason is I always build my universal apps using 3 classes for each module (screen), for example

1. LoginViewController  // this inherits from BaseViewController and holds common code for both ipad and iphone 
2. LoginViewController_iphone // custom logic for iphone only
3. LoginViewController_ipad // custom logic for ipad only

The cool part with that is I'm using controllers without suffixes around the code because they all extend from BaseViewController and it has overriden alloc method, which does smart logic and auto picks correct class upon calling VC alloc/init.

Now, as we all started slowly to transition to Swift, I managed to override and implement alloc method in Swift 1.2 as well. Here's the implementation:

class BaseViewController: UIViewController {

  override class func alloc() -> BaseViewController {

    var viewControllerClassName : String = NSStringFromClass(self)

    if ((viewControllerClassName.lowercaseString.rangeOfString("ipad") == nil) && (viewControllerClassName.lowercaseString.rangeOfString("iphone") == nil)) {

        switch (UIDevice.currentDevice().userInterfaceIdiom) {

        case .Pad:

            viewControllerClassName += "_ipad";

        case .Phone:

            viewControllerClassName += "_iphone";

        default:

            viewControllerClassName += "";
        }

        let viewControllerClass : AnyClass = NSClassFromString(viewControllerClassName)

        return viewControllerClass.alloc() as! BaseViewController

    } else {

        return super.alloc() as! BaseViewController
    }
}

Today, I downloaded Xcode 7 beta 6 with Swift 2 and tried to compile the project but got annoying surprise message "alloc() is unavailable in Swift: use object initializers instead". Well, I don't mind the other devs prefer using a different approach, however having more flexibility is better than having less. Has anybody an idea how to override creation of class object and add the custom logic?

Upvotes: 0

Views: 1451

Answers (2)

Nikolai Ruhe
Nikolai Ruhe

Reputation: 81878

The behavior you describe would not work on pure Swift types. There's no proper Swift concept for doing a similar thing in Swift (at least none that I'm aware of).

When resorting to Objective-C runtime trickery it seems OK to implement these tricks in Objective-C.

Upvotes: 1

user4151918
user4151918

Reputation:

Alloc being callable was an oversight, according to Chris Lattner, the developer of Swift.

You're going to have to migrate to object initializers.

Upvotes: 1

Related Questions