xcode iPhone 读/写 .plist 文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9335475/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
iPhone read/write .plist file
提问by Deni
I'm making a application where I need to store some information the user have provided. I try to use a .plist file to store the information, I found this:
我正在制作一个应用程序,我需要在其中存储用户提供的一些信息。我尝试使用 .plist 文件来存储信息,我发现:
NSString *filePath = @"/Users/Denis/Documents/Xcode/iPhone/MLBB/data.plist";
NSMutableDictionary* plistDict = [[NSMutableDictionary alloc] initWithContentsOfFile:filePath];
[plistDict setValue:@"Man" forKey:@"Gender"];
[plistDict writeToFile:filePath atomically: YES];
The problem is that the application will only work as long as I'm testing it in the iPhone simulator. I've tried this Changing Data in a Plistbut without luck. I have also read something about that I need to add it to my bundle, but how?
问题是该应用程序只有在我在 iPhone 模拟器中测试时才能工作。我试过这个在 Plist 中更改数据但没有运气。我也读过一些关于我需要将它添加到我的包中的内容,但是如何呢?
New code:
新代码:
- (IBAction)segmentControlChanged{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *plistLocation = [documentsDirectory stringByAppendingPathComponent:@"data.plist"];
NSMutableDictionary* plistDict = [[NSMutableDictionary alloc] initWithContentsOfFile:plistLocation];
if (Gender.selectedSegmentIndex == 0) {
[plistDict setObject:@"Man" forKey:@"Gender"];
[plistDict writeToFile:plistLocation atomically: YES];
}
else
{
[plistDict setObject:@"Women" forKey:@"Gender"];
[plistDict writeToFile:plistLocation atomically: YES];
}
}
回答by Mrunal
I guess you have added your plist file to your resources folder in Xcode (where we place image, if not then you need to place that first). Resources data goes to [NSBundle mainBundle]
by default and iOS does not allow us to change data inside bundle. So first you need to copy that file to Documents Directory.
我猜您已经将 plist 文件添加到 Xcode 中的资源文件夹中(我们放置图像的位置,如果没有,则需要先放置它)。资源数据[NSBundle mainBundle]
默认进入,iOS 不允许我们更改 bundle 中的数据。所以首先你需要将该文件复制到文档目录。
Here is the code for copying file from NSBundle
to the Documents directory.
这是将文件复制NSBundle
到 Documents 目录的代码。
- (NSString *)copyFileToDocumentDirectory:(NSString *)fileName {
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask,
YES);
NSString *documentsDir = [paths objectAtIndex:0];
NSString *documentDirPath = [documentsDir
stringByAppendingPathComponent:fileName];
NSArray *file = [fileName componentsSeparatedByString:@"."];
NSString *filePath = [[NSBundle mainBundle]
pathForResource:[file objectAtIndex:0]
ofType:[file lastObject]];
NSFileManager *fileManager = [NSFileManager defaultManager];
BOOL success = [fileManager fileExistsAtPath:documentDirPath];
if (!success) {
success = [fileManager copyItemAtPath:filePath
toPath:documentDirPath
error:&error];
if (!success) {
NSAssert1(0, @"Failed to create writable txt file file with message \
'%@'.", [error localizedDescription]);
}
}
return documentDirPath;
}
Now you can use the returned documentDirPath
to access that file and manipulate (Read/Write) over that.
现在您可以使用返回的documentDirPath
来访问该文件并对其进行操作(读/写)。
The plist structure is:
plist的结构是:
<array>
<dict>key-value data</dict>
<dict>key-value data</dict>
</array>
Here is code to write data into plist file:
这是将数据写入 plist 文件的代码:
/* Code to write into file */
- (void)addToMyPlist {
// set file manager object
NSFileManager *manager = [NSFileManager defaultManager];
// check if file exists
NSString *plistPath = [self copyFileToDocumentDirectory:
@"MyPlistFile.plist"];
BOOL isExist = [manager fileExistsAtPath:plistPath];
// BOOL done = NO;
if (!isExist) {
// NSLog(@"MyPlistFile.plist does not exist");
// done = [manager copyItemAtPath:file toPath:fileName error:&error];
}
// NSLog(@"done: %d",done);
// get data from plist file
NSMutableArray * plistArray = [[NSMutableArray alloc]
initWithContentsOfFile:plistPath];
// create dictionary using array data and bookmarkKeysArray keys
NSArray *keysArray = [[NSArray alloc] initWithObjects:@"StudentNo", nil];
NSArray *valuesArray = [[NSArray alloc] initWithObjects:
[NSString stringWithFormat:@"1234"], nil];
NSDictionary plistDict = [[NSDictionary alloc]
initWithObjects:valuesArray
forKeys:keysArray];
[plistArray insertObject:poDict atIndex:0];
// write data to plist file
//BOOL isWritten = [plistArray writeToFile:plistPath atomically:YES];
[plistArray writeToFile:plistPath atomically:YES];
plistArray = nil;
// check for status
// NSLog(@" \n written == %d",isWritten);
}
回答by Nick
Are you using that same path on your device? Apps on a device are sandboxed and can only read/write files in their documents directory. Grab that file path like thisand append your plist name. This approach will also work on the simulator.
您是否在设备上使用相同的路径?设备上的应用程序被沙盒化,只能读取/写入其文档目录中的文件。像这样获取该文件路径并附加您的 plist 名称。这种方法也适用于模拟器。
Try this:
尝试这个:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *plistLocation = [documentsDirectory stringByAppendingPathComponent:@"myplist.plist"];