我的应用程序在应用程序进程的任何时候以某种方式将NSData(包含书签文件引用)列表保存到NSUserDefaults:
NSMutableArray *bookmarkedURLs = [[NSMutableArray alloc] init];
[bookmarkedURLs addObject:bookmark]; // 'bookmark' is a NSData object
[[NSUserDefaults standardUserDefaults] setObject:bookmarkedURLs forKey:@"AppBookmarks"];
[[NSUserDefaults standardUserDefaults] synchronize];
当应用程序启动时,我检查了NSUserDefaults以填充已保存的NSData列表:
bookmarkedURLs = [[[NSUserDefaults standardUserDefaults] objectForKey:@"AppBookmarks"] mutableCopy];
if (bookmarkedURLs.count == 0)
{
bookmarkedURLs = [[NSMutableArray alloc] init];
NSLog(@"INITIALIZED");
}
else
{
NSLog(@"STORES NSDATA LIST");
....
}
我遇到的问题我可以按照以下步骤订购:
因此,每当NSUserDefaults没有保存数据并保存了值时,它就不会首次加载或保存。在那之后,任何保存和加载的尝试都在起作用。
答案 0 :(得分:0)
试试这个:
NSMutableArray *bookmarkedURLs = [[NSMutableArray alloc] init];
[bookmarkedURLs addObject:bookmark]; // 'bookmark' is a NSURL object
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:bookmarkedURLs forKey:@"AppBookmarks"];
[defaults synchronize];
我希望这可以帮到你。
答案 1 :(得分:0)
你可以做点什么,
NSUserDefaults *myDefaults = [NSUserDefaults standardUserDefaults];
// for example
NSURL *url1; // your url1
NSURL *url2; // your url2
//Set data to userdefaults
NSMutableArray *arr = [[NSMutableArray alloc]initWithObjects:url1,url2, nil]; // Store urls directly in array
NSData *bookMarkdata = [NSKeyedArchiver archivedDataWithRootObject:arr]; // convert whole array in data
[myDefaults setObject:bookMarkdata forKey:@"AppBookmarks"]; // save that data object to userdefaults
[myDefaults synchronize];
//Retreive data from userdefaults
NSData *resultData = [myDefaults objectForKey:@"AppBookmarks"]; //retrieve data from user defaults
NSMutableArray *resultArr = [NSKeyedUnarchiver unarchiveObjectWithData:resultData]; // get result array from data