2

I have a class XMLUtil, that wraps some xml parsing functionality. The class has one generic parameter T. The class also acts as the NSXMLParserDelegate to the NSXMLParser delegator.

class XMLUtil<T>: NSObject, NSXMLParserDelegate{
    ...
    ...

    init(){
        parser = NSXMLParser(data: NSData)
        parser.delegate = self
        parser.parse()
    }

    ...
    ...
    //delegate method implementations

}

The problem:

When my XMLUtil class is a generic class, the delegate methods never get called. They do however, when I implement the XMLUtil class without generic parameters

These two questions seem to be of similar nature

Swift Generic class as delegate

NSURLConnection Delegate Methods Not Called In Generic Class

Is there anything in the documentations that would explain this behavior? Is this intended or is it a bug?

Community
  • 1
  • 1
TheBaj
  • 1,091
  • 1
  • 10
  • 22
  • Yes, the links that you cite to tell you the answer. A generic class cannot be the delegate for a Cocoa class. It's not a bug... it is a feature that has not been implemented yet. I don't know if it will ever be implemented. It may not be possible. But it is a current limitation. – Aaron Rasmussen Aug 13 '15 at 22:53

1 Answers1

3

When my XMLUtil class is a generic class

But Objective-C knows nothing of generic classes. So there is no way to show your XMLUtil class to Objective-C. Thus, it cannot serve as NSXMLParser's delegate; NSXMLParser is an Objective-C class and cannot see your XMLUtil class if it is generic.

One easy way to see this is to try to mark your XMLUtil class as @objc. You will fail; the compiler will stop you. There is no way to show this class to Objective-C.

matt
  • 515,959
  • 87
  • 875
  • 1,141
  • Interesting. So does the compiler just act as though I the line `parser.delegate = self` didn't exist? Also, why doesn't it stop me from assigning a generic class as a delegate to an Objective-C class? – TheBaj Aug 13 '15 at 23:04
  • "Also, why doesn't it stop me from assigning a generic class as a delegate to an Objective-C class" That is a _very_ good question. You would think the compiler would stop you earlier, somehow. Personally, I regard this as a bug; the compiler should be more helpful. Letting you do something that isn't in fact going to work is not very nice. – matt Aug 13 '15 at 23:27
  • I take it that declaring the individual delegate methods `@objc` doesn't help? You can't say e.g. `@objc func parserDidStartDocument` etc. and have them be called? I wouldn't expect it to work but it's worth a try. – matt Aug 13 '15 at 23:30
  • Hi Matt, quick question, how can I set delegate = self, if I cannot instantiate an object because it is a generic class which I don't have access to in the other class, yet I want the generics class to call a function in the other class, hence the need for delegate? – Marin Dec 17 '16 at 19:44