Swift generics: EXC_BAD_ACCESS when trying to access class property - ios

It seems a class, which uses generics in swift, sometimes cannot properly determine object type.
Consider the following model structure:
class BaseModel: NSObject, Equatable, Printable {
var id: String = ""
override var description: String {
return "id: \(id)"
}
override func isEqual(object: AnyObject?) -> Bool {
if let object = object as? BaseModel {
return object.id == id
}
else {
return super.isEqual(object)
}
}
}
class Image: BaseModel {
var image: UIImage!
}
I also have parsers, which should parse/serialize objects:
class AbstractParser<T: BaseModel where T: Equatable>: NSObject {
func convertFromParseObject(object: NSObject) -> T {
var entity = T()
......
return updateEntityWithParseObject(object, entity: entity)
}
func updateEntityWithParseObject(object: NSObject, entity: T) -> T {
fatalError("This method must be overridden")
}
}
class ImageParser<T: Image>: AbstractParser<Image> {
override func updateEntityWithParseObject(object: NSObject, entity: Image) -> Image {
println("\(entity)")
println("\(entity.id)")
// The line below outputs BaseModel, shouldn't it be Image instead?
println("\(NSStringFromClass(entity.classForCoder))")
// EXC_BAD_ACCESS here:
println("\(entity.image)")
return entity
}
}
The app crashes when I try to access entity.image.
For some reasons Swift thinks that entity object is BaseModel, not Image.
Playground file: https://drive.google.com/file/d/0B6agzpK_lR6JQUlhMFoxaGw1akU/view?usp=sharing

Related

Instantiating classes stored in metatype Dictionary

I've followed the solution at Make a Swift dictionary where the key is "Type"? to create dictionaries that can use a class type as keys.
What I want to do is: I have one dictionary that should store class types with their class type (aka metatype) as keys, too:
class MyScenario {
static var metatype:Metatype<MyScenario> {
return Metatype(self)
}
}
var scenarioClasses:[Metatype<MyScenario>: MyScenario.Type] = [:]
Then I have methods to register and execute scenarios:
public func registerScenario(scenarioID:MyScenario.Type) {
if (scenarioClasses[scenarioID.metatype] == nil) {
scenarioClasses[scenarioID.metatype] = scenarioID
}
}
public func executeScenario(scenarioID:MyScenario.Type) {
if let scenarioClass = scenarioClasses[scenarioID.metatype] {
let scenario = scenarioClass()
}
}
... Problem is in the last line:
Constructing an object of class type 'MyScenario' with a metatype
value must use a 'required' initializer.
It looks like the compiler is confused at that point since I cannot use 'required' at that assignment. Does anyone have an idea how I would have to instantiate the scenarioClass in executeScenario()?
This must do the job.
import Foundation
struct Metatype<T> : Hashable
{
static func ==(lhs: Metatype, rhs: Metatype) -> Bool
{
return lhs.base == rhs.base
}
let base: T.Type
init(_ base: T.Type)
{
self.base = base
}
var hashValue: Int
{
return ObjectIdentifier(base).hashValue
}
}
public class MyScenario
{
var p: String
public required init()
{
self.p = "any"
}
static var metatype:Metatype<MyScenario>
{
return Metatype(self)
}
}
var scenarioClasses:[Metatype<MyScenario>: MyScenario.Type] = [:]
public func registerScenario(scenarioID:MyScenario.Type)
{
if (scenarioClasses[scenarioID.metatype] == nil)
{
scenarioClasses[scenarioID.metatype] = scenarioID
}
}
public func executeScenario(scenarioID:MyScenario.Type)
{
if let scenarioClass = scenarioClasses[scenarioID.metatype]
{
let scenario = scenarioClass.init()
print("\(scenario.p)")
}
}
// Register a new scenario
registerScenario(scenarioID: MyScenario.self)
// Execute
executeScenario(scenarioID: MyScenario.self)
// Should print "any"

Subclassing a Typhoon assembly to override methods not working

I am subclassing a Typhoon assembly such that stubbed implementations are returned, for unit testing purposes.
My assembly looks something like this:
class RealAssembly : TyphoonAssembly {
public dynamic func instanceToStubOut() -> AnyObject {
return TyphoonDefinition.withClass(SomeRealWorldClass.self)
}
public dynamic func instanceToTest() -> AnyObject {
return TyphoonDefinition.withClass(ClassToTest.self, configuration: { (definition : TyphoonDefinition!) -> Void in
definition.useInitializer("initWithObjectToStub:", parameters: { (initializer : TyphoonMethod!) -> Void in
initializer.injectParameterWith(self.instancetoStubOut())
})
})
}
}
My test class is solely for testing the instance of type ClassToTest, and I want to test it with the initializer-injected dependency on the object of type SomeRealWorldClass to be stubbed out. So I subclass RealAssembly so that instanceToStubOut() is overridden to return my stub object.
class MyTestClass : XCTestCase {
var assembly : TestAssembly!
class TestAssembly : RealAssembly {
override dynamic func instanceToStubOut() -> AnyObject {
return TyphoonDefinition.withClass(TestClass.self)
}
}
#objc
class TestClass : NSObject, ClassToStubOut {
func methodToStubOut() { /* do nothing */ }
}
override func setUp() {
super.setUp()
self.assembly = TestAssembly().activate()
}
override func tearDown() {
self.assembly = nil
super.tearDown()
}
func testStuff() {
let testingInstance = self.assembly.instanceToTest()
XCTAssertTrue(testingInstance.doStuff(), "doStuff returns true")
}
}
I expected this to work, but it doesn't. Typhoon seems to inject an uninitialized object instead of ever calling TestAssembly.instanceToStubOut()
Am I doing something wrong? Should I take a different approach?
EDIT: Here is some code you can paste into a Swift Playground that demonstrates the problem. The last line shows c.otherInstance returning nil :
import Typhoon
#objc
class BaseClass : NSObject {
var otherInstance : OtherProtocol!
func doIt() -> String {
return self.otherInstance.doStuff()
}
}
#objc
protocol OtherProtocol {
func doStuff() -> String
}
#objc
class OtherImpl : NSObject, OtherProtocol {
func doStuff() -> String {
return "OtherClass"
}
}
#objc
class StubClass : NSObject, OtherProtocol {
func doStuff() -> String {
return "Stubbed out"
}
}
class BaseAssembly : TyphoonAssembly {
dynamic func baseObject() -> AnyObject {
return TyphoonDefinition.withClass(BaseClass.self,
configuration: { (def : TyphoonDefinition!) -> Void in
def.injectProperty("otherInstance", with: self.otherObject())
})
}
dynamic func otherObject() -> AnyObject {
return TyphoonDefinition.withClass(OtherImpl.self)
}
}
var assembly = BaseAssembly()
assembly.activate()
var b = assembly.baseObject() as! BaseClass
b.doIt()
#objc
class TestAssembly : BaseAssembly {
override func otherObject() -> AnyObject {
return TyphoonDefinition.withClass(StubClass.self)
}
}
var testAssembly = TestAssembly()
testAssembly.activate()
var c = testAssembly.baseObject() as! BaseClass
c.otherInstance // this shouldn't be nil
Edit:
While patching is an option, as outlined in #Herman's answer below, what was attempted in the question is a supported feature, however there was a regression bug preventing it from working correctly.
The regression bug has been fixed in Typhoon 3.2.2 and so now both patching and overriding an assembly are again options for configuring Typhoon for a particular use-case.
Patching
There is a patching feature for this purpose in Typhoon. Look here.
For example:
class StubClass : NSObject, OtherProtocol {
#objc func doStuff() -> String {
return "Stubbed out"
}
}
let assembly = BaseAssembly()
assembly.activate()
let b = assembly.baseObject() as! BaseClass
print(b.doIt())
let testAssembly = BaseAssembly().activate()
let patcher = TyphoonPatcher()
patcher.patchDefinitionWithSelector("otherObject") { () -> AnyObject! in
return StubClass()
}
testAssembly.attachPostProcessor(patcher)
let c = testAssembly.baseObject() as! BaseClass
print(c.doIt())

Type "MyClass" does not conform to protocol "Collection_Delegate"

I have a class MyClass implementing a generic function of a delegate Collection_Delegate.
My classes Collection and Item are superclasses for some specific classes
protocol Collection_Delegate {
func onFetchAllCompleted<T, U where T: Collection<U>, U: Item>(collection: T, error: String?)
}
class Collection<T>: Item {
private var items: [T]
override init (communicator: CG_API_Communicator) {
items = [T]()
super.init(communicator: communicator)
}
internal func fetchAll() {
fatalError(notImplemented)
}
internal func onFetchAllCompleted(error: String?, json: JSON?) {
fatalError(notImplemented)
}
internal func appendItem(item: T) {
self.items.append(item)
}
internal func getItems() -> [T] {
return self.items
}
}
class Item {
var itemDataRaw: JSON?
func toString() -> String? {
var retval: String?
if let value: String = itemDataRaw?.rawString(encoding: NSUTF8StringEncoding) {
retval = value
} else {
retval = "Something went badly wrong"
}
return retval
}
}
Now in some subclasses of Collection I want to call the generic onFetAllCompleted function of the delegate avery subclass has. But the class implementing the Collection_Delegate protocol causing compiler errors
class MyClass: Collection_Delegate { // Error
func onFetchAllCompleted<T, U where T: Collection<U>, U: Item>(collection: T, error: String?){
println("MyClass.onFetchAllCompleted:\(_stdlib_getTypeName(collection))") // This displays the right class name of the subclasses
let item: Item = collection.getItems()[0] //Error
let string = item.toString()
}
}
Here we go. The class **MyClass* gets the error
Type "MyClass" does not conform to protocol "Collection_Delegate"
Within the generic function I get the error
'U' is not convertible to 'Item'
So what am I doing wrong? Why doesn't the generic stuff work?
I think you over complicated things a bit with your generic function declaration. If I understood you correctly your onFetchAllCompleted function takes parameter T which is Collection of U's and U is an Item. If that is correct the above expression can be simplified like this : onFetchAllCompleted function takes parameter T which is Collection of Items. So your protocol and class should look like this
protocol Collection_Delegate {
func onFetchAllCompleted<T: Collection<Item>>(collection: T, error: String?)
}
class MyClass: Collection_Delegate {
func onFetchAllCompleted<T: Collection<Item>>(collection: T, error: String?){
println("MyClass.onFetchAllCompleted:\(_stdlib_getTypeName(collection))") // This displays the right class name of the subclasses
let item: Item = collection.getItems()[0] //Error
let string = item.toString()
}
}
Let me know if this helped you

How to create custom initilizers with Cocoa Realm

I have a swift project with Realm in it where I would like to store objects using RLMObject, however I cannot create a custom init, as it will throw an error.
I Have tried
import Foundation
import Realm
class Foo: RLMObject {
dynamic var First: String = ""
dynamic var Last: String = ""
init(first: String, last: String) {
super.init()
self.First = first
self.Last = last
}
override init(object: AnyObject?) {
super.init(object:object)
}
override init(object value: AnyObject!, schema: RLMSchema!) {
super.init(object: value, schema: schema)
}
override init(objectSchema: RLMObjectSchema) {
super.init(objectSchema: objectSchema)
}
}
Which was suggested here

Generic class inheritance in Swift

I have the following class:
class BaseCache<T: Equatable>: NSObject {
var allEntities = [T]()
// MARK: - Append
func appendEntities(newEntities: [T]) {
....
}
}
Now I want to subclass it, but I get annoying error, that my type "does not conform to protocol 'Equatable'":
It seems generics in Swift are real pain-in-the-ass.
Your class definition of TrackingCache is wrong. It repeats the generic parameter:
class TrackingCache<AftershipTracking>: BaseCache<AftershipTracking> { }
It should be left out:
class TrackingCache: BaseCache<AftershipTracking> { }
This triggers the underlying swift error Classes derived from generic classes must also be generic. You can work around this issue by specifying a type parameter that is required to be or inherit from AftershipTracking:
class TrackingCache<T: AftershipTracking>: BaseCache<AftershipTracking> { }
Full example:
class BaseCache<T: Equatable>: NSObject {
var items: [T] = []
func appendItems( items: [T]) {
self.items += items
didAppendItems()
}
func didAppendItems() {} // for overriding
}
class AftershipTracking: NSObject {
var identifier: Int
init( identifier: Int) {
self.identifier = identifier
super.init()
}
}
extension AftershipTracking: Equatable { }
func ==( lhs: AftershipTracking, rhs: AftershipTracking) -> Bool {
return lhs.identifier == rhs.identifier
}
class TrackingCache<T: AftershipTracking>: BaseCache<AftershipTracking> {
override func didAppendItems() {
// do something
}
}
let a = TrackingCache<AftershipTracking>()
let b = TrackingCache<AftershipTracking>()
a.appendItems( [AftershipTracking( identifier: 1)])
b.appendItems( [AftershipTracking( identifier: 1)])
let result = a.items == b.items // true
this should work: < swift 4 >
class TrackingCache<T: AftershipTracking>: BaseCache<T>
Another example:
protocol P {
}
class C: P {
}
class CS: C {
}
class L<T:P> {
let c: T
init(_ c: T) {
self.c = c
}
}
class LS<T:CS>:L<T> {
}
let i = LS(CS())
i.c
c is CS now.

Resources