IOS上的消息處理機制同Android相比是更大的豐富拓展,IOS既有像類似Android的監聽機制也由類似的廣播方式。但通常來講可以分為這樣三類:
1.Notification(通知)
2.Helper objects(輔助對象)
3.Target-action(目標-動作模型)
如果是建一個IOS項目做個demo,大量的代碼誰都會受不了,於是我使用的mac上的Command Line程序。
我們都知道在IOS系統內部有一個一直在運轉的RunLoop,就像是一個活著的死循環,說他是死循環是因為只要系統不關機它都在後台運轉著,說他是活的是因為他最終還是在做著一些有用的工作,處理一些我們看得見看不見的處理。
在測試者三中方式的時候我建了一個Logger類,通過這個類來展現出三種方式的區別:
Logger.h:
#import@interface Logger : NSObject{ NSMutableData *incomingData; } - (void)sayhello:(NSTimer *)t; -(void)zoneChange:(NSNotification *)note; @end
#import "Logger.h"
@implementation Logger
-(void)sayhello:(NSTimer *)t{
NSLog(@"hello 你好!");
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
NSLog(@"received %lu bytes",[data length]);
if (!incomingData) {
incomingData = [[NSMutableData alloc] init];
}
[incomingData appendData:data];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection{
NSLog(@"got it all");
NSString *string = [[NSString alloc] initWithData:incomingData encoding:NSUTF8StringEncoding];
incomingData = nil;
NSLog(@"strnig has %lu charachers",[string length]);
NSLog(@"the all string: %@",string);
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
NSLog(@"connection fail %@",[error localizedDescription]);
incomingData = nil;
}
-(void)zoneChange:(NSNotification *)note{
NSLog(@"the system time zone has changed");
}
-(void)dealloc{
#pragma 釋放該對象的“通知”
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
@end
Logger 中的各種方法都是在後面的運行中會訪問的我會在下面一一說明:
在main.m中對上面的Logger類進行一個初始:
@autoreleasepool {
Logger *logger = [[Logger alloc] init];
//這裡就是寫三種處理機制的代碼了;
[[NSRunLoop currentRunLoop] run];
}後面的 [[NSRunLoop
currentRunLoop] run];就相當於開啟那個無限循環。
比如我們想要通知系統當時區改變時候要調用Logger中的zoneChange方法。我們可以這樣:(這就是一個簡單地Notification機制)
[[NSNotificationCenter defaultCenter] addObserver:logger selector:@selector(zoneChange:) name:NSSystemClockDidChangeNotification object:nil];
NSURL *url = [NSURL URLWithString:@"http://localhost"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
__unused NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:logger startImmediately:YES];而Target-action也是同樣可以用下面一行代碼來解決:
__unused NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:logger selector:@selector(sayhello:) userInfo:nil repeats:YES];