2

Can I Override swift per-module namespaces for my NSCoding classes?

I basically need:

Module1.MyCodedClass == Module2.MyCodedClass

I know I can put MyCodedClass in a dynamic framework and I use that approach but that seems like overkill :D

maybe set a custom module for a certain class?


OR tell the nscoder that class a == class b ...

Daij-Djan
  • 49,552
  • 17
  • 113
  • 135
  • Maybe I'm misunderstanding. Why do you need the same class definition in 2 separate frameworks? If they are slightly different, than they wouldn't be equal, and if they are exactly the same, that's code duplication. – Matthew Seaman Aug 20 '16 at 20:56
  • app a and app b... and as I said, a framework seems overkill... just to get the same namespace. [apple discouragess linking too many frameworks too ;)] – Daij-Djan Aug 22 '16 at 13:19
  • and I dont want to share code between a and b. there shall only be a common 'contract' between the implementers – Daij-Djan Aug 22 '16 at 13:20
  • Could you place MyCodedClass in the same Workspace (but outside of either app) and then just have each app reference the same file? That might mess with Version Control though. – Matthew Seaman Aug 22 '16 at 15:58

1 Answers1

2

If the primary issue is NSCoding, I've done this with the @objc() attribute before the class declaration like this:

@objc(MyCodedClass) class MyCodedClass: NSObject, NSCoding {
...
}

This causes NSCoder to use just the name of your class without the module name attached (the way that it would do it if the class were implemented in Objective-C)

Also - here is something I just learned that totally fixed a problem I was facing. I had a couple versions of my app ship before I did the above @objc() fix on my encoded classes, so there are basically encoded versions of Module1.MyCodedClass floating around (stored in a database) and I needed to be able to decode those as simply MyCodedClass objects now. You can do this in NSKeyedUnarchiver like this:

[NSKeyedUnarchiver setClass:[MyCodedClass class] forClassName:@"Module1.MyCodedClass"];

So far, in my testing it works perfectly...as long as you set the class for the old classname prior to ever attempting to decode an object, you should be set. Whenever you attempt to decode Module1.MyCodedClass objects, it will decode them as MyCodedClass objects.

chrismc
  • 88
  • 10
  • thanks! thats @objc was it .. I used setClass but I didn't really like that. though I agree it is really useful in your case! :) – Daij-Djan Jan 19 '17 at 22:56