1. 程式人生 > >NSNotificationCenter的幾種基礎用法

NSNotificationCenter的幾種基礎用法

除了用的比較多的delegate和block之外,還有就是通知。通知的功能比前面兩種要強大的多,當然也不能隨便濫用,否則,不知道會發生社麼.

1.一般註冊、傳送通知

  首先要註冊通知

[[NSNotificationCenterdefaultCenter]addObserver:selfselector:@selector(textViewChange) name:notificationNameobject:(id)object];

然後就是當需要通知別的類的時候就傳送通知

    [[NSNotificationCenter defaultCenter]postNotificationName:notificationName object:nil];

當然啦,註冊和傳送時的通知名必須要一樣,object就是要給的資料啦

2、監聽一些view的變化

例如:監聽UITextField、UITextView文字框內length的變化

 [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(textViewChange) name:UITextViewTextDidChangeNotification object:textView];

目前遇到也就這麼兩種.