我已经阅读了几篇关于此的帖子,但我无法修复错误。如果有人可以请求帮助。
这是我使用的代码。我有一个名为list的NSMutableArray。
-(void) awakeFromNib
{
prefs=[[NSUserDefaults standardUserDefaults]retain];
if ([prefs arrayForKey:@"list"]) {
list=[[NSMutableArray alloc]initWithArray:[prefs objectForKey:@"list"]];
}
else {
list=[[NSMutableArray alloc]init];
}
}
-(void)saveData
{
NSLog(@"saving data!");
[prefs setObject:list forKey:@"list"];
}
- (void)dealloc {
[self saveData];
[prefs synchronize];
[prefs release];
}
答案 0 :(得分:1)
您不能将UIView实例存储在用户默认值中,而只能存储在属性列表中可序列化的对象(请参阅here)另外,正如@Justin所说,不要保留或释放默认对象。
答案 1 :(得分:0)
谢谢。但是,我之前已经读过你无法在NSUserDefaults中保存NSMutableArray,所以我试图将它转换为NSData然后使用它。
这是我的ViewController.m文件:
-(id)initWithCoder:(NSCoder *)aDecoder
{
self=[[calViewController alloc]init];
if (self!=nil) {
self.list=[aDecoder decodeObjectForKey:@"list"];
}
return self;
}
-(void)encodeWithCoder:(NSCoder *)aCoder
{
[aCoder encodeObject:list forKey:@"list"];
}
这是我的AppDelegate.m文件:
-(void) applicationDidFinishLaunching:(UIApplication *)application
{
NSLog(@"Application did finish launching");
defaults=[NSUserDefaults standardUserDefaults];
NSData *dataRepresentingSavedArray=[defaults objectForKey:@"lastArray"];
if (dataRepresentingSavedArray!=nil) {
NSArray *oldSavedArray = [NSKeyedUnarchiver unarchiveObjectWithData:dataRepresentingSavedArray];
if (oldSavedArray != nil)
{
listAr = [[NSMutableArray alloc] initWithArray:oldSavedArray];
else
{
listAr = [[NSMutableArray alloc] init];
NSLog(@"listAr: %@",listAr);
}
}
}
-(void) applicationWillTerminate:(UIApplication *)application
{
[[NSUserDefaults standardUserDefaults] setObject:[NSKeyedArchiver archivedDataWithRootObject:listAr] forKey:@"lastArray"];
}
我之前从未使用过UserDefaults而且我完全糊涂了。我已经阅读了所有的文档,但我似乎没有把它弄好!
修改强>
-(void) applicationDidFinishLaunching:(UIApplication *)application
{
NSLog(@"Application did finish launching");
defaults=[NSUserDefaults standardUserDefaults];
if ([defaults objectForKey:@"lastArray"]) {
NSData *dataRepresentingSavedArray=[defaults objectForKey:@"lastArray"];
if (dataRepresentingSavedArray!=nil) {
NSArray *oldSavedArray = [NSKeyedUnarchiver unarchiveObjectWithData:dataRepresentingSavedArray];
if (oldSavedArray != nil)
listAr = [[NSMutableArray alloc] initWithArray:oldSavedArray];
}
}
else
{
listAr = [[NSMutableArray alloc] init];
NSLog(@"listAr: %@",listAr);
}
}