兒童類 Children 定時器定期減少快樂值與飢餓值,低於閾值時發送通知。保姆類 Nurse 註冊觀察者,收到通知執行陪玩或餵食,恢復數值。
happyValue、hungryValue。init 啟動 1 秒定時器 timeAction:。postNotificationName:object: 發送 happyValueNotification 或 hungryValueNotification,object 為 self。Children 引用。initWithChildren: 中 addObserver:selector:name:object: 註冊兩個通知,object:nil 表示接收任意發送者。happyValueChange、hungryValueChange: 調用 play、feed 恢復數值。dealloc 中 removeObserver: 移除所有通知,防止野指針。// 發送通知
[[NSNotificationCenter defaultCenter] postNotificationName:@"happyValueNotification" object:self];
// 註冊觀察者
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(happyValueChange)
name:@"happyValueNotification"
object:nil];
// 移除觀察者(推薦在 dealloc)
[[NSNotificationCenter defaultCenter] removeObserver:self];
main 創建 Children 和 Nurse,啟動 RunLoop。Nurse,執行響應邏輯。object 參數可用於過濾發送者,此處用 nil 接收所有。NSNotificationCenter 實現了鬆耦合的觀察者模式,適合跨層級、多對多的事件傳遞。本例展示了完整的發送-註冊-響應-清理生命週期,是 iOS 開發中通信機制的基礎範例。