Search code examples
ioswatchkitnscodingnskeyedarchiverapple-watch

How can I import a model object file into my watch extension if it has a lot of dependencies


I am working on building a companion app to an existing iOS app that is quite large and has pieces that are somewhat archaic. There is a list in the iOS app that has items that are of type ClassA lets say. Persistence is handled by archiving these objects to disk and reading back out when needed.

I changed the location of the save to be in a shared container that the watch app can read, but the watch extension can't make sense of the list because it doesn't know about ClassA. Fair enough. I add ClassA.m to by Compile Sources in the target settings and then we have a ton of errors due to imports and dependencies associated with ClassA.

I start adding more and more classes and before long it is throwing errors in files all across the project that seemingly have nothing to do with ClassA.

So now I am wondering if this is all required for what I am trying to do. I just want to be able to read an archive of objects of type ClassA in my watch extension, do I need to import half of the iOS app into the watch extension?


Solution

  • If I understand you correctly your ClassA is a model class which stores some data and processes it. In this case I would recommend you to refactor your ClassA so it will have only properties and methods that don't depends on other classes and move all other methods to class extension (or several extensions if appropriate).
    Example:
    Before:

    class DependentClass {
       func goodFunction(a: Int) -> Int{ return a * 5 }
    
       func dependantFunction(b: AnotherDependantClass) -> AnotherDependantClass2{ ... }
    }
    

    After:

    class DependentClass {
       func goodFunction(a: Int) -> Int{ return a * 5 }
    }
    
    //In another file
    extension DependentClass{
       func dependantFunction(b: AnotherDependantClass) -> AnotherDependantClass2{ ... }
    
    }
    

    EDIT
    Example in Objective-C:
    Before:

    //DependentClass.h
    @class AnotherDependantClass;
    @class AnotherDependantClass2;
    
    @interface DependentClass : NSObject
    
    -(int)goodFunction:(int)a;
    -(AnotherDependantClass2 *)dependantFunction:(AnotherDependantClass *)a;
    
    @end
    

    After:

    //DependentClass.h
    @interface DependentClass : NSObject
    
    -(int)goodFunction:(int)a;
    
    @end
    
    //DependentClass+Dependencies.h
    @class AnotherDependantClass;
    @class AnotherDependantClass2;
    
    @interface DependentClass (Dependencies)
    
    -(AnotherDependantClass2 *)dependantFunction:(AnotherDependantClass *)a;
    
    @end
    

    After that include your DependentClass.m in your watch extension and add #import "DependentClass+Dependencies.h" where appropriate. Hope this will help.