關於MVC模型的NSNotification用法

來源:互聯網
上載者:User

標籤:style   blog   io   color   os   ar   使用   for   sp   

剛開始接觸iOS,開始對Model View Controller 模型不太熟悉,最近在使用Model給Controller傳遞資料時候瞭解了關於

NSNotification的一些用法,寫出來記錄一下,程式碼片段如下:

當PhotoDataBaseContext被更新時候,會廣播一個通知,通知一般都是NSDictionary類,包含了一個Key和Value,Value是發送內容的地址;

接受訊息的一方必須要在發起廣播之前開始監聽,因為廣播是一瞬間的事情,當錯過了廣播的時間之後就再也接受不到通知了,所以一般Controller會在繪製xib開始建立監聽,那麼就用到 -(void)awakeFromNib,搶在廣播之前建立監聽,這樣就可以在廣播的時候收到通知,從而得到更新,因為接收到的資料的地址,所以以後在改地址被更新的資料在Controller內也能被更新。歡迎大家給一下不同的建議;

-(BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{    self.photoDataBaseContext  = [self createMainQueueManagedObjectContext];    [self startFickrFetch];- (void) setPhotoDataBaseContext:(NSManagedObjectContext *)photoDataBaseContext{        [NSTimer scheduledTimerWithTimeInterval:10*60 target:self selector:@selector(startFickrFetch:) userInfo:nil repeats:YES];//Call startFlickrFetch:            _photoDataBaseContext = photoDataBaseContext;    NSDictionary * userInfo = self.photoDataBaseContext ? @{ PhotoDatabaseAvailabilityContext : self.photoDataBaseContext } :nil;    //當發送通知時候,被通知的對象必須先於發送通知之前建立監聽資訊    //因為發送通知時候,通知在發送之後,如果沒有被監聽,那麼就再也接受不通知,    //所以要被通知者要優先建立監聽,否則機會丟失資訊    [[NSNotificationCenter defaultCenter] postNotificationName:PhotoDatabaseAvailabilityNotification object:self userInfo:userInfo];}//Call startFlickrFetch:- (void) startFickrFetch:(NSTimer*)time{    [self startFickrFetch];}
// 寫在控制器代碼內 ViewController
-(void)awakeFromNib{ NSLog(@"notification"); [[NSNotificationCenter defaultCenter] addObserverForName:PhotoDatabaseAvailabilityNotification object:nil queue:nil usingBlock:^(NSNotification *not){ self.manageObjectContext = not.userInfo[PhotoDatabaseAvailabilityContext]; }];}

 

關於MVC模型的NSNotification用法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.