Search code examples
iosobjective-ccocoa-touchuiviewcontrollerextending-classes

Split UIViewController implementation into multiple source files


I'm new to iOS development and I'm looking for a good example. Can someone give me a link?

My problem:

I made a project with some UIViewControllers, but I have a controller that has a lot of methods. How can I split my UIViewController into multiple classes?

Finally, I want just split my UIViewController into multiple files but I want my UIViewController working as if all the methods were in the same file.

If someone can give me a good book or explain me how it works that would be great.


Solution

  • You can use categories. You create a separate header and implementation file for each category, where the header looks something like:

    @interface MyClass (SomethingMethods)
    
    ... // Function declarations
    
    @end
    

    Then, you implement it like this:

    @implementation MyClass (SomethingMethods)
    
    ... // Implementation
    
    @end
    

    This allows you to split the class into separate source files by what the methods do or whatever you want. However, remember every category must have a unique name. The name is not really used anywhere in any important way, but it must be unique, otherwise you will get compile errors.

    Note that categories do not allow you to declare properties or instance variables. You can only declare and implement methods. This means that you will have to declare all your instance variables and @propertys in your main source file and implementation. See the official Apple documentation on categories for more info.