2

I like to create a instance of a class just by the name of the class

here sample code from a playground

import Cocoa

public protocol FCoding : class {
  init(coder aDecoder: FCoder)
  func encodeWithCoder(aCoder: FCoder)
}

// just some func for demo
public protocol FCoder {
    func encodeString(strv: String?, forKey key: String)
    func decodeStringForKey(key: String) -> String?
}

class TestCoder : FCoder {
  var name = "TestCoder"

  init () {}

  func encodeString(strv: String?, forKey key: String) {}

  func decodeStringForKey(key: String) -> String? {
    return "111"
  }
}

class Test : FCoding {

  var text : String

  required init(coder aDecoder: FCoder) {
    var value = aDecoder.decodeStringForKey("1")

    if value != nil {
        text = value!
    } else {
        text = "!!!"
    }
  }

  func encodeWithCoder(aEncoder: FCoder) {
     aEncoder.encodeString(text, forKey: "1")
  }
}

var testCoder = TestCoder()

let className = NSStringFromClass(Test)

let objClass = NSClassFromString(className) as! FCoding.Type

//let obj = objClass(coder: testCoder)

If I uncomment the last statement, the compiler crash with a segmenation fault: 11 (in XCode Version 6.3.1 (6D1002))

  • Is there any other way to realize this?
  • Is there a bug in the code?
  • Do you have the same problem?

There is a disucssion about a similar topic here: Swift language NSClassFromString

Essential difference is here we speak about a pur Swift class (and not NSObject subclasses) which have no init method by default.

Community
  • 1
  • 1
Stephan
  • 4,263
  • 2
  • 24
  • 33

1 Answers1

0

The problem seems fixed in Swift 2.0 (tested in the Beta 2 of Xcode)

The following call deliver a instance:

let obj = objClass.init(coder: testCoder)
Stephan
  • 4,263
  • 2
  • 24
  • 33