Proper Objective-C Helper “Wannabe” Private methods?

前端 未结 3 539
南旧
南旧 2021-02-06 18:01

While I hate to beat a horse to death on this subject (I\'ve read through various articles about this), but would just like to get more opinions on this matter before I create m

3条回答
  •  广开言路
    2021-02-06 18:27

    If you just need a reusable set of code that absolutely cannot be overridden by a subclass, you could just make a regular C function instead of a method. If the function is declared within the scope of the class @implementation block, it can still get access to all the private ivars of the object. You'd need to pass in a pointer to self, though, since a function isn't bound to a particular object

    So it would look like this:

    static BOOL isInValidState(MyClass *);
    
    @implementation MyClass
    
    static BOOL isInValidState(MyClass *self) {
        if (self->somePrivateIvar == nil) {
            return NO;
        }
    
        if ([self->someString isEqualToString:@"pigsAreFlying"]) {
            return NO;
        }
    
        return YES;
    }
    
    - (void)method1 {
        if (isInValidState(self) == NO) {
            return;
        }
        // Do whatever method 1 does
    }
    
    - (void)method2 {
        if (isInValidState(self) == NO) {
            return;
        }
        // Do whatever method 2 does
    }
    
    @end
    

    Since functions are not part of the method list of a class, this error checking method cannot ever be overridden. Since we declared it static, it is only accessible within the scope of this file, which means that it's effectively private; it cannot be called by an object of any other class.

提交回复
热议问题