His*_*erg 1 cocoa cocoa-touch objective-c cocoa-design-patterns ios
我很困惑 - 我无法理解代表的目的是什么?
默认情况下创建的Application Delegate是可以理解的,但在某些情况下我看到过类似的内容:
@interface MyClass : UIViewController <UIScrollViewDelegate> {
UIScrollView *scrollView;
UIPageControl *pageControl;
NSMutableArray *viewControllers;
BOOL pageControlUsed;
}
//...
@end
Run Code Online (Sandbox Code Playgroud)
有什么<UIScrollViewDelegate>用?
它是如何工作的以及为什么使用它?
Jac*_*kin 12
<UIScrollViewDelegate>是说,类符合该UIScrollViewDelegate 协议.
这实际意味着该类必须实现UIScrollViewDelegate协议中定义的所有必需方法.就那么简单.
如果您愿意,可以将您的班级符合多种协议:
@implementation MyClass : UIViewController <SomeProtocol, SomeOtherProtocol>
Run Code Online (Sandbox Code Playgroud)
使类符合协议的目的是:a)将类型声明为协议的符合,因此您现在可以将此类型分类id <SomeProtocol>,这对于此类对象可能属于的委托对象更好,并且b)它告诉编译器不要警告您实现的方法未在头文件中声明,因为您的类符合协议.
这是一个例子:
Printable.h
@protocol Printable
- (void) print:(Printer *) printer;
@end
Run Code Online (Sandbox Code Playgroud)
Document.h
#import "Printable.h"
@interface Document : NSObject <Printable> {
//ivars omitted for brevity, there are sure to be many of these :)
}
@end
Run Code Online (Sandbox Code Playgroud)
Document.m
@implementation Document
//probably tons of code here..
#pragma mark Printable methods
- (void) print: (Printer *) printer {
//do awesome print job stuff here...
}
@end
Run Code Online (Sandbox Code Playgroud)
然后,您可以拥有符合Printable协议的多个对象,然后可以将其用作对象中的实例变量PrintJob:
@interface PrintJob : NSObject {
id <Printable> target;
Printer *printer;
}
@property (nonatomic, retain) id <Printable> target;
- (id) initWithPrinter:(Printer *) print;
- (void) start;
@end
@implementation PrintJob
@synthesize target;
- (id) initWithPrinter:(Printer *) print andTarget:(id<Printable>) targ {
if((self = [super init])) {
printer = print;
self.target = targ;
}
return self;
}
- (void) start {
[target print:printer]; //invoke print on the target, which we know conforms to Printable
}
- (void) dealloc {
[target release];
[super dealloc];
}
@end
Run Code Online (Sandbox Code Playgroud)