首先分析以下 优势
观察者模式 是每个继承NSObject 对象都会有的一个小东西
例如下载一批图片 想要等待 图片都下载好 给使用者 就可以使用delegate
被观察对象
#import <Foundation/Foundation.h>
typedef enum {
testSuccessNotGot = 0,
testSuccess,
testFail
}testType;
@interface test : NSObject{
NSInteger selectInt;
}
@property (nonatomic,assign) testType testGotState;
- (void)setText;
@end
#import "test.h"
@implementation test
@synthesize testGotState = _testGotState;
- (void)executeShow{
_testGotState = testSuccess;
}
- (id)init{
self = [super init];
if (self) {
[self performSelector:@selector(executeShow) withObject:nil afterDelay:3];
}
return self;
}
- (void)setText{
_testGotState = testFail;
}
想要观察这个类
self.mTest = [[[test alloc]init ] autorelease];
[self addObserver:self forKeyPath:@"mTest.testGotState" options:NSKeyValueObservingOptionInitial context:self.mTest];
- (void) observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{
if (context == self.mTest) {
if ([keyPath isEqualToString:@"mTest.testGotState"]) {
switch (self.mTest.testGotState) {
case 0:
NSLog(@"开始时");
break;
case 1:
NSLog(@"成功!");
break;
case 2:
NSLog(@"失败!");
break;
default:
break;
}
}
}
}
然后根据不同的情况去处理吧 ! 呵呵