Objective-C: @class Directive before @interface?

前端 未结 4 1715
星月不相逢
星月不相逢 2020-11-28 20:08

What is the difference between these two class declarations? I don\'t understand why @class is utilized here. Thanks.

@class TestClass;

@interface TestCl         


        
4条回答
  •  暖寄归人
    2020-11-28 20:47

    @class is pretty handy when you need to define a protocol for an object that will usually interact with the object whose interface you are also defining. Using @class, you can keep the protocol definition in header of your class. This pattern of delegation is often used on Objective-C, and is often preferable to defining both "MyClass.h" and "MyClassDelegate.h". That can cause some confusing import problems

    @class MyClass;
    
    @protocol MyClassDelegate
    
    - (void)myClassDidSomething:(MyClass *)myClass
    - (void)myClass:(MyClass *)myClass didSomethingWithResponse:(NSObject *)reponse
    - (BOOL)shouldMyClassDoSomething:(MyClass *)myClass;
    - (BOOL)shouldMyClass:(MyClass *)myClass doSomethingWithInput:(NSObject *)input
    
    @end
    
    // MyClass hasn't been defined yet, but MyClassDelegate will still compile even tho
    // params mention MyClass, because of the @class declaration.
    // You're telling the compiler "it's coming. don't worry".
    // You can't send MyClass any messages (you can't send messages in a protocol declaration anyway),
    // but it's important to note that @class only lets you reference the yet-to-be-defined class. That's all.
    // The compiler doesn't know anything about MyClass other than its definition is coming eventually.
    
    @interface MyClass : NSObject
    
    @property (nonatomic, assign) id delegate;
    
    - (void)doSomething;
    - (void)doSomethingWithInput:(NSObject *)input
    
    @end
    

    Then, when you are using the class, you can both create instances of the class as well as implement the protocol with a single import statement

    #import "MyClass.h"
    
    @interface MyOtherClass()
    
    @property (nonatomic, strong) MyClass *myClass;
    
    @end
    
    @implementation MyOtherClass
    
    #pragma mark - MyClassDelegate Protocol Methods
    
    - (void)myClassDidSomething:(MyClass *)myClass {
    
        NSLog(@"My Class Did Something!")
    
    }
    
    - (void)myClassDidSomethingWithResponse:(NSObject *)response {
    
        NSLog(@"My Class Did Something With %@", response);
    
    }
    
    - (BOOL)shouldMyClassDoSomething {
    
        return YES;
    
    - (BOOL)shouldMyClassDoSomethingWithInput:(NSObject *)input {
    
        if ([input isEqual:@YES]) {
    
            return YES;
    
        }
    
        return NO;
    
    }
    
    
    - (void)doSomething {
    
        self.myClass = [[MyClass alloc] init];
        self.myClass.delegate = self;
        [self.myClass doSomething];
        [self.myClass doSomethingWithInput:@0];
    
    }
    

提交回复
热议问题