我在plist中的信息未保存

时间:2012-04-26 16:25:01

标签: iphone objective-c ios ipad

我在plist中有一些设置,但是当我杀死我的应用程序时,我丢失了存储在那里的所有数据。

这是我正在使用的代码:

·H

@property (retain, nonatomic) NSString *plistFilePath;
-(IBAction)setHomepage:(id)sender;

.m

@syntehzise plistFilePath;

-(IBAction)setHomepage:(id)sender{
plistFilePath = [NSString stringWithString:[[NSBundle mainBundle] pathForResource:@"settings" ofType:@"plist"]];
    NSMutableDictionary *data= [[NSMutableDictionary alloc] initWithContentsOfFile:plistFilePath];
    [data setObject:@"http://www.google.com" forKey:@"Homepage"];
    [data writeToFile:plistFilePath atomically:YES];
    [data release];  

}

我做错了吗?我应该使用不同的类或不同的方法吗?请帮助我,因为我不知道为什么我存储了很好的信息,但是当我杀死应用程序时,我失去了它。

2 个答案:

答案 0 :(得分:1)

应用程序包是只读的。如果要分发文件然后进行更新,请在应用程序第一次运行时将其从软件包移动到文档文件夹。

答案 1 :(得分:1)

如前所述,捆绑包是只读的。

尽量避免在复制的plist中设置'settings',因为plists只是管理的另一件事。相反,为什么不使用默认plist中的NSUserDefaults and import your defaults。例如,将新plist添加到项目中,并将其添加到您的委托:

// Get the shared defaults object
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];

// Register the defaults each time the app loads
NSString *defaultsFile = [[NSBundle mainBundle] pathForResource:@"Defaults" ofType:@"plist"];
NSDictionary *defaultsDict = [NSDictionary dictionaryWithContentsOfFile:defaultsFile];
[defaults registerDefaults:defaultsDict];

现在您可以保存这样的数据:

// Store the data
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:@"http://mattmelton.co.uk" forKey:@"HomePage"];
[defaults synchronize];

并像这样检索它:

// Retrieve data
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *homePage = [defaults objectForKey:@"HomePage"];

您不必担心外部文件。当然,您的默认plist可以是平台,用户或设备特定的!

希望这有帮助!