非正式协议
- 非正式协议就是类别,即凡是NSObject或其子类的类别,都是非正式协议。
协议(protocol)
- 简单的说就是声明一些方法写到.h中(方法有2种,一是必须实现,二是选择实现)
协议的作用
- 供其他的类去遵守,如果一个类遵守了一个协议,就应该实现这个协议中定义的必须要实现的方法
协议的声明
#import <Foundation/Foundation.h>
@protocol PersonProtocol <NSObject>
- (NSInteger )accpetSpeeds;
@end
协议的使用
#import "ViewController.h"
#import "PersonProtocol.h"
@interface ViewController ()<PersonDelegate>
@end
协议代理的demo实例
#import <Foundation/Foundation.h>
@protocol PersonProtocol <NSObject>
- (NSInteger )accpetSpeeds;
@end
@interface Model : NSObject
- (NSInteger )accpetSpeeds;
@end
#import "Model.h"
#import "PersonProtocol.h"
@interface Model ()<PersonProtocol>
@end
@implementation Model
- (NSInteger )accpetSpeeds
{
return 100.f;
}
@end
#import <Foundation/Foundation.h>
@class Person;
@protocol PersonDelegate <NSObject>
- (void)personRun:(Person *)person speeds:(NSInteger)speeds;
@end
@interface Person : NSObject
@property (nonatomic, weak)id <PersonDelegate>delegate;
- (void)run:(NSInteger)speeds;
@end
#import "Person.h"
@implementation Person
- (void)run:(NSInteger)speeds
{
if (self.delegate && [self.delegate respondsToSelector:@selector(personRun:speeds:)]) {
[self.delegate personRun:self speeds:0.5];
}
}
@end
#import "ViewController.h"
#import "Person.h"
#import "PersonProtocol.h"
#import "Model.h"
@interface ViewController ()<PersonDelegate>
@property (nonatomic, assign)NSInteger age;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
Person *p = [[Person alloc] init];
p.delegate = self;
[p run: 50];
Model *mode = [Model new];
id <PersonProtocol> object = mode;
[self testData:object];
}
- (void)personRun:(Person *)person speeds:(NSInteger)speeds
{
NSLog(@"speeds====:%ld",speeds);
}
- (void)testData:(id<PersonProtocol>)model
{
self.age = [model accpetSpeeds];
NSLog(@"self.age ===:%ld",self.age);
}
@end
网友评论