當你需要爲一個對象定義一個協議時,@class會非常方便,該對象通常會與你定義的接口的對象進行交互。使用@class,您可以將協議定義保留在類的標題中。這種授權模式經常用在Objective-C上,通常最好定義「MyClass.h」和「MyClassDelegate.h」。這可能會導致一些混亂的進口問題
@class MyClass;
@protocol MyClassDelegate<NSObject>
- (void)myClassDidSomething:(MyClass *)myClass
- (void)myClass:(MyClass *)myClass didSomethingWithResponse:(NSObject *)reponse
- (BOOL)shouldMyClassDoSomething:(MyClass *)myClass;
- (BOOL)shouldMyClass:(MyClass *)myClass doSomethingWithInput:(NSObject *)input
@end
@interface MyClass : NSObject
@property (nonatomic, assign) id<MyClassDelegate> delegate;
- (void)doSomething;
- (void)doSomethingWithInput:(NSObject *)input
@end
然後,當你使用這個類,你既可以創建類的實例以及與一個import語句
#import "MyClass.h"
@interface MyOtherClass()<MyClassDelegate>
@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];
}
我希望我可以給另一個+1只爲'雞,滿足蛋' – lukya 2013-07-05 13:25:44
順便說一句,它確實恢復到'id'評估。 – jheld 2014-05-21 16:19:05
爲什麼某些人在他們的.h文件中放入'@ class',然後在.m文件中導入必要的頭文件,以及其他人可能只是將當前類頭文件中的.h文件導入?只是好奇,謝謝。 @bbum – 2014-05-30 20:01:01