Objective C - 2 .m files for one .h file?

前端 未结 3 1054
日久生厌
日久生厌 2021-01-21 18:37

My question is, that I would know how to use 2 .m files for one objectclass also for one header (.h)

I have a big method with 20000+ lines and I would, that this method

相关标签:
3条回答
  • 2021-01-21 18:52

    You have several approaches:

    1. you could split your methods into 2 different categories:

      //-- MyClass1.m
      @implementation MyClass (part1)
      
      @end
      
      //-- MyClass2.m
      @implementation MyClass (part2)
      
      @end
      

      I defined 2 categories for symmetry reason; of course you also need a "base" @implementation of your class (i.e., without the category specifier); you can choose whether you define a "base" and and extension category, or "base" and two categories, etc...

    2. or you might try including the second .m file inside of the first one:

          //-- MyClass1.m
          @implementation MyClass
      
          <first part>
      
          #include "MyClass2.m"
      
          @end
      

    Both should work.

    Let alone the possibility of refactoring your class, which would be the best option.

    0 讨论(0)
  • 2021-01-21 18:52

    I have a big method with 20000+ lines

    Okay, that's your problem right there. That's what you need to fix. Splitting things up into two implementation files is a distraction. This is your main problem. There's virtually no circumstances where this is not a terrible way of doing things.

    Methods should be a few dozen lines long at most. If you find yourself writing a method that is longer than that, you need to break the functionality down into smaller pieces. Create smaller methods to do part of the job, then call those methods from your original method.

    Classes should not be this size. If you are creating a file with more than a couple of thousand lines of code in, it's a huge warning sign that one class is responsible for too much functionality. You should break the functionality down into several classes, each of which is responsible for one key piece of functionality.

    I get a link error

    If you post a sentence like this to Stack Overflow, it should be accompanied by the actual error you get.

    0 讨论(0)
  • 2021-01-21 19:09

    You can make the excessively long method a category of the class:

    MyClass.h:

    @interface MyClass
    @property ...
    -(void) method;
    ...
    @end
    
    @interface MyClass (BigMethod)
    -(void) bigMethod;
    @end
    

    MyClass.m:

    @implementation MyClass
    -(void) method
    {
        ...
    }
    ...
    @end
    

    BigMethod.m

    @implementation MyClass (BigMethod)
    -(void) bigMethod
    {
        ...
    }
    @end
    

    However, a 20k line method is absurd. You should really refactor it.

    0 讨论(0)
提交回复
热议问题