2010-07-02 76 views
0

我正在尝试使用下面的代码来保存当前通知的当前列表。 NSArray明确列出了它将使用的对象的类型,这意味着我不能在一个充满UILocalNotification对象的数组中使用它。但是,UILocalNotifications确实实现了NSCoding,这使我相信必须有一种简单的方法来序列化/反序列化这个对象列表。我需要自己执行编码和文件持久性吗?另外,有没有办法获得关于写入失败原因的更多信息?我可以将UILocalNotifications数组写入磁盘吗?

- (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"]; 
} 
} 

回答

2

首先,代码

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%确定它会工作。但试试看看会发生什么。

+0

很酷,谢谢柯比!我不知道NSKeyedArchiver存在。配对与NSKeyedUnarchiver和我得到它的工作。谢谢! – 2010-07-06 02:22:59