Как я могу сохранять, извлекать, удалять и обновлять свои данные в файле Plist в ios?
Я создаю приложение для iPhone, в котором я получаю имя, логотип и имя игрока во всех странах. Я хочу сохранить эти данные в .plist
вместо сервера sqlite
. Я не знаю, как создать файл plist в DocumentDirectory
и сохранить данные.
Пожалуйста, предложите мне, как сохранить данные в файле plist.
Ответы
Ответ 1
Я просматриваю скриншот и шаг за шагом. Следуйте за этим, и вы получите ответ.
Сначала вам нужно создать список свойств через свой Xcode.
Шаг: 1
![enter image description here]()
Шаг: 2
![enter image description here]()
Шаг: 3
Сохраните данные в действии кнопки сохранения:
// Take 3 array for save the data .....
-(IBAction)save_Action:(id)sender
{
NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0];
NSString *plistPath = [documentsPath stringByAppendingPathComponent:@"manuallyData.plist"];
[self.nameArr addObject:self.nameField.text];
[self.countryArr addObject:self.countryField.text];
[self.imageArr addObject:@"image.png"];
NSDictionary *plistDict = [[NSDictionary alloc] initWithObjects: [NSArray arrayWithObjects: self.nameArr, self.countryArr, self.imageArr, nil] forKeys:[NSArray arrayWithObjects: @"Name", @"Country",@"Image", nil]];
NSError *error = nil;
NSData *plistData = [NSPropertyListSerialization dataFromPropertyList:plistDict format:NSPropertyListXMLFormat_v1_0 errorDescription:&error];
if(plistData)
{
[plistData writeToFile:plistPath atomically:YES];
alertLbl.text = @"Data saved sucessfully";
}
else
{
alertLbl.text = @"Data not saved";
}
}
// Data is saved in your plist and plist is saved in DocumentDirectory
Шаг: 4
Получить данные из файла plist:
NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0];
NSString *plistPath = [documentsPath stringByAppendingPathComponent:@"manuallyData.plist"];
if (![[NSFileManager defaultManager] fileExistsAtPath:plistPath])
{
plistPath = [[NSBundle mainBundle] pathForResource:@"manuallyData" ofType:@"plist"];
}
NSDictionary *dict = [[NSDictionary alloc] initWithContentsOfFile:plistPath];
self.nameArr = [dict objectForKey:@"Name"];
self.countryArr = [dict objectForKey:@"Country"];
Шаг: 5
Удалить данные из файла plist:
NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0];
NSString *plistPath = [documentsPath stringByAppendingPathComponent:@"manuallyData.plist"];
NSMutableDictionary *dictionary = [NSMutableDictionary dictionaryWithContentsOfFile:(NSString *)plistPath];
self.nameArr = [dictionary objectForKey:@"Name"];
self.countryArr = [dictionary objectForKey:@"Country"];
[self.nameArr removeObjectAtIndex:indexPath.row];
[self.countryArr removeObjectAtIndex:indexPath.row];
[dictionary writeToFile:plistPath atomically:YES];
Шаг: 6
Обновите свои данные в окне "Обновить". Действие:
NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0];
NSString *plistPath = [documentsPath stringByAppendingPathComponent:@"manuallyData.plist"];
if (![[NSFileManager defaultManager] fileExistsAtPath:plistPath])
{
plistPath = [[NSBundle mainBundle] pathForResource:@"manuallyData" ofType:@"plist"];
}
self.plistDic = [[NSDictionary alloc] initWithContentsOfFile:plistPath];
[[self.plistDic objectForKey:@"Name"] removeObjectAtIndex:self.indexPath];
[[self.plistDic objectForKey:@"Country"] removeObjectAtIndex:self.indexPath];
[[self.plistDic objectForKey:@"Image"] removeObjectAtIndex:self.indexPath];
[[self.plistDic objectForKey:@"Name"] insertObject:nameField.text atIndex:self.indexPath];
[[self.plistDic objectForKey:@"Country"] insertObject:countryField.text atIndex:self.indexPath];
[[self.plistDic objectForKey:@"Image"] insertObject:@"dhoni.jpg" atIndex:self.indexPath];
[self.plistDic writeToFile:plistPath atomically:YES];
Ответ 2
SWIFT 3.0
Ниже приведен код для чтения и записи данных в файле .plist.
- Создайте файл data.plist.
-
Убедитесь, что корневой объект имеет тип Dictionary.
class PersistanceViewControllerA: UIViewController {
@IBOutlet weak var nationTextField: UITextField!
@IBOutlet weak var capitalTextField: UITextField!
@IBOutlet weak var textView: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
displayNationAndCapitalCityNames()
//Get Path
func getPath() -> String {
let plistFileName = "data.plist"
let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
let documentPath = paths[0] as NSString
let plistPath = documentPath.appendingPathComponent(plistFileName)
return plistPath
}
//Display Nation and Capital
func displayNationAndCapitalCityNames() {
let plistPath = self.getPath()
self.textView.text = ""
if FileManager.default.fileExists(atPath: plistPath) {
if let nationAndCapitalCitys = NSMutableDictionary(contentsOfFile: plistPath) {
for (_, element) in nationAndCapitalCitys.enumerated() {
self.textView.text = self.textView.text + "\(element.key) --> \(element.value) \n"
}
}
}
}
//On Click OF Submit
@IBAction func onSubmit(_ sender: UIButton) {
let plistPath = self.getPath()
if FileManager.default.fileExists(atPath: plistPath) {
let nationAndCapitalCitys = NSMutableDictionary(contentsOfFile: plistPath)!
nationAndCapitalCitys.setValue(capitalTextField.text!, forKey: nationTextField.text!)
nationAndCapitalCitys.write(toFile: plistPath, atomically: true)
}
nationTextField.text = ""
capitalTextField.text = ""
displayNationAndCapitalCityNames()
}
}
вывод:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Canada</key>
<string>Ottawa</string>
<key>China</key>
<string>Beijin</string>
<key>Germany</key>
<string>Berlin</string>
<key>United Kingdom</key>
<string>London</string>
<key>United States of America</key>
<string>Washington, D.C.</string>
</dict>
</plist>
![введите описание изображения здесь]()
Ответ 3
Простой пример
NSString *filePath=[[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:@"country.plist"];
// ADD Plist File
NSMutableArray *arr=[[NSMutableArray alloc]initWithObjects:@"India",@"USA" ,nil];
[arr writeToFile:filePath atomically:YES];
//Update
NSFileManager *fm=[NSFileManager defaultManager];
[arr removeObjectIdenticalTo:@"India"];
[fm removeItemAtPath:filePath error:nil];
[arr writeToFile:filePath atomically:YES];
// Read
NSMutableArray *arr=[[NSMutableArray alloc]initWithContentsOfFile:filePath];
Ответ 4
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:@"plist.plist"];
NSFileManager *fileManager = [NSFileManager defaultManager];
if (![fileManager fileExistsAtPath: path]) {
path = [documentsDirectory stringByAppendingPathComponent: [NSString stringWithFormat: @"yourfilename.plist"]];
}
NSMutableDictionary *data = [[NSMutableDictionary alloc] initWithContentsOfFile: path];
NSFileManager *fileManager = [NSFileManager defaultManager];
NSMutableDictionary *data;
if ([fileManager fileExistsAtPath: path]) {
data = [[NSMutableDictionary alloc] initWithContentsOfFile: path];
} else {
// If the file doesn’t exist, create an empty dictionary
data = [[NSMutableDictionary alloc] init];
}
//To insert the data into the plist
int value = 5;
[data setObject:[NSNumber numberWithInt:value] forKey:@"value"];
[data writeToFile: path atomically:YES];
//To retrieve the data from the plist
NSMutableDictionary *savedStock = [[NSMutableDictionary alloc] initWithContentsOfFile: path];
int savedvalue;
savedvalue = [[savedStock objectForKey:@"value"] intValue];
NSLog(@"%d", savedvalue);
Ответ 5
Ссылка: https://medium.com/@javedmultani16/save-and-edit-delete-data-from-plist-in-ios-debfc276a2c8
Вы уже создали список. Этот список останется таким же в приложении. Если вы хотите редактировать данные в этом списке, добавлять новые данные в список или удалять данные из списка, вы не можете вносить изменения в этот файл.
Для этого вам нужно будет сохранить свой лист в каталоге документов. Вы можете редактировать свой список сохраненных в каталоге документов.
\\Save plist in document directory as:
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"Data" ofType:@"plist"]; NSDictionary *dict = [[NSDictionary alloc] initWithContentsOfFile:filePath]; NSDictionary *plistDict = dict;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *error = nil;
NSData *plistData = [NSPropertyListSerialization dataFromPropertyList:plistDict
format:NSPropertyListXMLFormat_v1_0 errorDescription:&error];
if (![fileManager fileExistsAtPath: plistPath]) {
if(plistData)
{
[plistData writeToFile:plistPath atomically:YES];
}
}
else
{ }
\\Retrieve data from Plist as:
NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask,
YES);
NSString *documentsPath = [paths objectAtIndex:0];
NSString *plistPath = [documentsPath stringByAppendingPathComponent:@"Data.plist"];
NSDictionary *dict = [[NSDictionary alloc] initWithContentsOfFile:plistPath];
NSArray *usersArray = [dict objectForKey:@"Object1"];
Ответ 6
Вы уже создали список. Этот список останется таким же в приложении. Если вы хотите изменить данные в этом списке, добавить новые данные в список или удалить данные из списка, вы не можете вносить изменения в этот файл.
Для этого вам нужно будет сохранить свой лист в каталоге документов. Вы можете редактировать свой список сохраненных в каталоге документов.
Сохранить список в каталоге документов как:
NSString *filePath = [[NSBundle mainBundle] pathForResource:@'Data' ofType:@'plist']; NSDictionary *dict = [[NSDictionary alloc] initWithContentsOfFile:filePath]; NSDictionary *plistDict = dict;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *error = nil;
NSData *plistData = [NSPropertyListSerialization dataFromPropertyList:plistDict
format:NSPropertyListXMLFormat_v1_0 errorDescription:&error];
if (![fileManager fileExistsAtPath: plistPath]) {
if(plistData)
{
[plistData writeToFile:plistPath atomically:YES];
}
}
else
{ }
Получить данные из Plist как:
NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask,
YES);
NSString *documentsPath = [paths objectAtIndex:0];
NSString *plistPath = [documentsPath stringByAppendingPathComponent:@"Data.plist"];
NSDictionary *dict = [[NSDictionary alloc] initWithContentsOfFile:plistPath];
NSArray *usersArray = [dict objectForKey:@"Object1"];
Вы можете редактировать удаление, добавлять новые данные в соответствии с вашими требованиями и снова сохранять список в Каталог документов.
Ref:https://medium.com/@javedmultani16/save-and-edit-delete-data-from-plist-in-ios-debfc276a2c8