首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

iOS AppDelegate 與 ViewController 傳遞字串資料:使用 NSUserDefaults

     編輯:程式設計綜合問答

場景

推播負載 (userInfo) 在 AppDelegate 接收,需傳遞給特定 ViewController 顯示。

方案:NSUserDefaults 暫存

AppDelegate.m

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    // 儲存推播資料
    [[NSUserDefaults standardUserDefaults] setObject:userInfo forKey:@"RemoteNotificationUserInfo"];
    [[NSUserDefaults standardUserDefaults] synchronize];
    
    // 發送通知通知 ViewController (可選)
    [[NSNotificationCenter defaultCenter] postNotificationName:@"RemoteNotificationReceived" object:nil userInfo:userInfo];
    completionHandler(UIBackgroundFetchResultNewData);
}

ViewController.m

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    // 取得資料
    NSDictionary *userInfo = [[NSUserDefaults standardUserDefaults] objectForKey:@"RemoteNotificationUserInfo"];
    if (userInfo) {
        // 更新 UI、導航至詳細頁...
        [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"RemoteNotificationUserInfo"]; // 用完清除
    }
}

// 或監聽通知即時反應
- (void)viewDidLoad {
    [super viewDidLoad];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleRemoteNotification:) name:@"RemoteNotificationReceived" object:nil];
}

- (void)handleRemoteNotification:(NSNotification *)notification {
    NSDictionary *userInfo = notification.userInfo;
    // 立即處理
}

替代方案比較

方案優點缺點適用場景
NSUserDefaults簡單、跨啟動持久化非即時、需主動讀取App 冷啟動由推播進入
NSNotificationCenter即時、解耦App 未啟動時收不到App 前景/背景運行中
單例/共享模型型別安全、即時需自行管理生命週期複雜資料流
Core Data / Realm結構化、查詢強大過重大量歷史記錄

最佳實務

  1. 冷啟動:AppDelegate didFinishLaunchingWithOptions 中檢查 launchOptions[UIApplicationLaunchOptionsRemoteNotificationKey],直接導航目標頁面。
  2. 前景/背景:NSNotificationCenter 廣播,目標 VC 監聽處理。
  3. 資料清理:讀取後移除 UserDefaults 快取,避免重複處理。
  4. iOS 10+:使用 UNUserNotificationCenterDelegate 統一處理推播展示與點擊回調。

組合使用 NSUserDefaults (冷啟動備份) + NSNotificationCenter (即時傳遞),可完整覆蓋推播資料傳遞需求。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved