簡體   English   中英

我可以將UILocalNotifications數組寫入磁盤嗎?

[英]Can I write an array of UILocalNotifications to disk?

我正在嘗試使用以下代碼來持久保存本地通知的當前列表。 NSArray明確列出了它將使用的對象的種類,這意味着我不能在充滿UILocalNotification對象的數組中使用此對象。 但是,UILocalNotifications確實實現了NSCoding,這使我相信必須有一種簡單的方法來序列化/反序列化此對象列表。 我需要自己進行編碼和文件持久性嗎? 此外,是否有辦法獲得有關寫入失敗原因的更多信息?

- (NSString*)getSavedNotifsPath {
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];

    return [documentsDirectory stringByAppendingString:@"saved_notifs.plist"];
}

- (void)prepareToHide {
UIApplication* app = [UIApplication sharedApplication];
NSArray *existingNotifications = [app scheduledLocalNotifications];
if (! [existingNotifications writeToFile:[self getSavedNotifsPath] atomically:NO] ) {
    // alert
    [self showSomething:@"write failed"];
}
}

首先,更改代碼

return [documentsDirectory stringByAppendingString:@"saved_notifs.plist"];

return [documentsDirectory stringByAppendingPathComponent:@"saved_notifs.plist"];

stringByAppendingPathComponent:如果需要,將確保在文件名之前包含斜杠(/)。

NSArray只能保存屬性列表對象,而UILocalNotification則不能。 而是嘗試使用NSKeyedArchiver。 例如:

- (void)prepareToHide {
   UIApplication* app = [UIApplication sharedApplication];
   NSArray *existingNotifications = [app scheduledLocalNotifications];
   NSString *path = [self getSavedNotifsPath];
   BOOL success = [NSKeyedArchiver archiveRootObject:existingNotifications toFile:path];
   if (! success ) {
      // alert
      [self showSomething:@"write failed"];
   }
}

使用NSKeyedUnarchiver從保存的文件中檢索陣列。

注意:我還沒有實際測試過,所以我不是100%確信它會工作。 但是嘗試一下,看看會發生什么。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM