我是 Objective-c 和 iOS 开发的新手,在我的课堂上我声明了委托协议。
我发现了几个这样做的例子,它们看起来都非常相似,但有一些区别,我想自己弄清楚并理解。
示例 1:
(链接 - https://stackoverflow.com/a/12660523/2117550和https://github.com/alexfish/delegate-example/blob/master/DelegateExample/CustomClass.h)
我的类.h
#import <BlaClass/BlaClass.h>
@class MyClass; // removed in example 2
@protocol MyClassDelegate <NSObject>
@optional
- (void) myClassDelegateMethod:(BOOL)value;
@end
@interface MyClass : NSObject
@property (nonatomic, weak) id <MyClassDelegate> delegate;
@end
我的班级.m
#import "MyClass.h"
@implementation MyClass
@synthesize delegate; // removed in example 2
- (void) myMethodToDoStuff {
[self.delegate myClassDelegateMethod:YES];
}
@end
示例 2:( 链接 - http://www.tutorialspoint.com/ios/ios_delegates.htm)
实际上除了这两个不同之外是相同的..
与他们不同的事情:
- 例1中我们
@class
在protocol之前声明,真的有必要吗?或者只是最佳实践。如果没有此声明,第二个示例可以正常工作。 - 在示例 1 中
@synthesize delegate
,据我了解,我们使用它为属性创建 getter/setter,但我们真的需要它吗?第二个例子没有这个。
这两个例子都很好,我只是想消除我心中的困惑。
谢谢!