代理協議在iphone開發中用了很多,幾乎每個項目中都有用到。
代理和被代理端,怎麼進行數據交互。
(1)協議的具體用法
(2)如何實現代理
(3)代理2端如何通訊
事件方法由人來實現;狗中存放有人的類;
這裡將信息匯報給主人;
定時器:狗每個1秒向人匯報。(初始化狗的時候就開始定時發送數據)
.m
timer = [NSTimer scheduledTimerWithTimeInterval:1.0f target:selfselector:
@selector(updataTimer:) userInfo:nilrepeats:YES];
意思是:[self updateTimer:nil];
- (void) updataTimer:(id)arg
{
barkCount ++;
//通知狗的主人
[delegatebark:self count:barkCount];
}
//這個函數在人中
- (void) bark:(Dog *)thisDog count:(int)count
{
}
不讓main函數退出:
while(1)
{
[[NSRunloopcurrentRunLoop] run];
}
存放狗的主人:
id delegate;//ownner 狗的主人
在人調用setDog方法時將,主人id存放進去。
定義一個人和狗通信的協議:
在狗中定義一個協議
@protocol DogBark
- (void) bark:(Dog *)thisDog Count:(int)count;
@end
id
delegate;//ownner 狗的主人
在人中實現這個協議
狗的聲明和協議的聲明:
@class Dog;//表示前向聲明
@protocol DogBark;//協議前向聲明
(1)協議的具體用法[事件通知;c語音中叫:回調指針]
(2)如何實現代理
(3)代理2端如何通訊
定義協議
// // Dog.h // DogAndPerson // // Created by ccy on 13-12-21. // Copyright (c) 2013年 ccy. All rights reserved. // #import#import "DogToPerson.h" @interface Dog : NSObject { int _dogID; id _delegate;//人的類 int barkCount; NSTimer * timer; } @property int dogID; @property (retain) id delegate; @end
// // DogToPerson.h // DogAndPerson // // Created by ccy on 13-12-21. // Copyright (c) 2013年 ccy. All rights reserved. // #import#import "Dog.h" @class Dog;//這裡一定要記得聲明 @protocol DogToPerson @optional - (void) dogBark:(Dog *) thisDog barkCount:(int) barkCount; @end
// // Dog.m // DogAndPerson // // Created by ccy on 13-12-21. // Copyright (c) 2013年 ccy. All rights reserved. // #import "Dog.h" @implementation Dog @synthesize dogID = _dogID; @synthesize delegate = _delegate; - (id)init { self = [super init]; if (self) { self.dogID = 0; barkCount = 0; timer = [NSTimer scheduledTimerWithTimeInterval:2.0f target:self selector:@selector(hand:) userInfo:nil repeats:YES]; } return self; } - (void)hand:(id)arg { NSLog(@"dog hand\n"); barkCount++; [self.delegate dogBark:self barkCount:barkCount]; } @end
person申明協議:
// // Person.h // DogAndPerson // // Created by ccy on 13-12-21. // Copyright (c) 2013年 ccy. All rights reserved. // #import#import "Dog.h" @interface Person : NSObject { Dog * _dog; } @property (retain) Dog * dog; @end
// // Person.m // DogAndPerson // // Created by ccy on 13-12-21. // Copyright (c) 2013年 ccy. All rights reserved. // #import "Person.h" @implementation Person @synthesize dog = _dog; - (void)dogBark:(Dog *)thisDog barkCount:(int)barkCount { NSLog(@"dogBark thisDogID:%d, barkCount:%d\n", thisDog.dogID, barkCount); } @end
// // main.m // DogAndPerson // // Created by ccy on 13-12-21. // Copyright (c) 2013年 ccy. All rights reserved. // #import#import "Dog.h" #import "Person.h" int main(int argc, const char * argv[]) { @autoreleasepool { // insert code here... NSLog(@"Hello, World!"); Person * xiaoLi = [[Person alloc] init]; Dog * dog1 = [[Dog alloc] init]; dog1.dogID = 1024; dog1.delegate = xiaoLi; xiaoLi.dog = dog1; [dog1 release]; while (1) { [[NSRunLoop currentRunLoop] run]; } [xiaoLi release]; } return 0; }