Kyle Decot
Kyle Decot

Reputation: 20825

Subclass NSMutableData in Swift

I am attempting to create a subclass of NSMutableData in Swift called ServiceProviderData which will receive two NSData instances, do some parsing (oversimplified in my example below) to create a new NSData instance that I then want to call super.init(data: data) with.

Attempting to implement this using the code below gives me:

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** initialization method -initWithBytes:length:copy:deallocator: cannot be sent to an abstract object of class Example.ServiceProviderData: Create a concrete instance!'

I've read that NSData/NSMutableData are part of a class cluster so my question is what methods/properties do I have to implement and how do I do this in swift?

class ServiceProviderData: NSMutableData {
    init?(originalResponseData: NSData, identityProviderResponseData: NSData) {

        // Here I'm just appending the two datas but this has 
        // been greatly simplified for demonstrative purposes...

        let data = NSMutableData(data: originalResponseData)
        data.appendData(identityProviderResponseData)

        super.init(data: data)
    }

    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

Upvotes: 0

Views: 663

Answers (1)

Daij-Djan
Daij-Djan

Reputation: 50119

Don't think there is any good reason to do this

You should just have class WRAP a data object IMHO

BUT

about class clusters: https://developer.apple.com/library/ios/documentation/General/Conceptual/CocoaEncyclopedia/ClassClusters/ClassClusters.html

A new class that you create within a class cluster must:

  • Be a subclass of the cluster’s abstract superclass
  • Declare its own storage
  • Override all initializer methods of the superclass
  • Override the superclass’s primitive methods (described below)

for NSData the primitive methods are bytes and length

Upvotes: 1

Related Questions