I have an api inside are the city's ID, I do not want to request data every time,I want to writeToFile as plist,but the first written is too slow and memory skyrocketing.
Is there any method I can use to make it into a plist as local file,so users do not have to write again
Plist file obtained in this way is no data on the xcode view, but in fact it has already been written, you can find data through code
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
NSString *plistPath = [paths objectAtIndex:0];
NSMutableArray *marr = [NSMutableArray array];
NSString *filename=[plistPath stringByAppendingPathComponent:#"city.plist"];
NSLog(#"filename == %#",filename);
[marr addObject:#"字符串"];
[marr writeToFile:filename atomically:YES];
If you are about to create Plist without programmatically then follow these steps :
Right Click on Files and Select 'New File...' option.
Choose Resources from OS X tab.
An option for Property List is available.
Select an give an appropriate name.
This gets added to your project.
You can create a property list in Objective-C if all of the objects in the aggregate derive from the NSDictionary, NSArray, NSString, NSDate, NSData, or NSNumber class.
Use following code:
//Get the documents directory path
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:#"plist.plist"] ];
}
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
[data setObject:#"iPhone 6 Plus" forKey:#"value"];
[data writeToFile:path atomically:YES];
//To retrieve the data from the plist
NSMutableDictionary *savedValue = [[NSMutableDictionary alloc] initWithContentsOfFile: path];
NSString *value = [savedValue objectForKey:#"value"];
NSLog(#"%#",value);
For more details click here
Apple has also put a demo project for creating plist file here.
I wrote a class that caches API responses, so later when u request Countries endpoint, it will check defined endpoints to cache, if it find it in list and it exist in cache, it will return the cached one and will not complete performing the HTTP request, in docs i provided steps how to implement it.
MGCacheManager
Following function take serilizable object(dictionary, array) as input and convert it into plist and write it in document disrectory of application:
+ (BOOL) writeBundelPlist : (NSString *) plistName with : (id) newPlistData {
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *plistPath = [documentsDirectory stringByAppendingPathComponent:plistName];
if (![fileManager fileExistsAtPath:plistPath]) {
NSString *bundle = [[NSBundle mainBundle] pathForResource:[plistName stringByDeletingPathExtension] ofType:[plistName pathExtension]];
NSLog(#"plistPath = %#", plistPath);
[fileManager copyItemAtPath:bundle toPath:plistPath error:&error];
}
return [newPlistData writeToFile:plistPath atomically:YES];
}
this method is very useful, thanks for evervone,thanks for rmaddy
do{
let data = try NSPropertyListSerialization.dataWithPropertyList(response.result.value as! NSMutableDictionary, format: NSPropertyListFormat.XMLFormat_v1_0, options: 0)
data.writeToFile(countryListPath, atomically: true)
}catch
{
}
Related
I am trying to save data in a NSMutableDictionary to a plist. Plist is already in the Resources folder. When I am trying to save the data to the plist using following code it returns YES which means data was successfully saved. But when I check the file data is not saved to it.
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); //1
NSString *documentsDirectory = [paths objectAtIndex:0]; //2
NSString *path = [documentsDirectory stringByAppendingPathComponent:#"userInfo.plist"]; //3
NSFileManager *fileManager = [NSFileManager defaultManager];
if (![fileManager fileExistsAtPath: path]){ //4 {
NSString *bundle = [[NSBundle mainBundle] pathForResource:#"userInfo" ofType:#"plist"]; //5
[fileManager copyItemAtPath:bundle toPath: path error:&error]; //6
}
BOOL b = [self.userInfoArray writeToFile:path atomically: YES];
NSLog(#"status %i ", b);
Anyone have solution of this ?
I think I was looking at the wrong file. Plist file in the Xcode does not change after saving the data. Instead, plist in the simulator is changing.
Normally I save data to a plist (just data that I don't really care if a JailBroken phone hacked, like users preferences and stuff) except when the user first launches the app I create the plist like so:
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *pathFirstTime = [documentsDirectory stringByAppendingPathComponent:#"FirstTime.plist"];
NSFileManager *fileManager = [NSFileManager defaultManager];
if (![fileManager fileExistsAtPath: pathFirstTime])
{
NSString *bundleFirstTime = [[NSBundle mainBundle] pathForResource:#"FirstTime" ofType:#"plist"];
[fileManager copyItemAtPath:bundleFirstTime toPath:pathFirstTime error:&error];
}
So I create a blank plist file in xcode and put it in the bundle and the first time the user launches the app it copies it to the documentsDirectory...
Is there anyway I can create the blank plist file in objective-c the first time that way I don't actually have to create one in Xcode and have it in the bundle but it will just get created automatically the first time the user launches the app...
Basically just avoiding this code: [fileManager copyItemAtPath:bundleFirstTime toPath:pathFirstTime error:&error];
[#{} writeToFile: pathFirstTime atomically: NO];
Create an NSArray or NSDictionary instance and use writeToFile:atomically:.
remove your whole code, this will do the trick
if(![[NSUserDefaults standardUserDefaults] objectForKey:#"FirstRun"]){
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *pathFirstTime = [documentsDirectory stringByAppendingPathComponent:#"MyPlistFile.plist"];
[#{} writeToFile: pathFirstTime atomically: YES];
[[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithBool:NO] forKey:#"FirstRun"];
}
Want to add a new record ?
NSString *pathFirstTime = [documentsDirectory stringByAppendingPathComponent:#"MyPlistFile.plist"];
NSMutableDictionary *mdic = [[NSMutableDictionary alloc] initWithDictionary:[NSDictionary dictionaryWithContentsOfFile:pathFirstTime]];
[mdic setObject:[NSNumber numberWithInt:3] forKey:#"user-selected-color-scheme"];
[mdic writeToFile: pathFirstTime atomically: YES];
Read the plist file later ?
NSString *pathFirstTime = [documentsDirectory stringByAppendingPathComponent:#"MyPlistFile.plist"];
NSMutableDictionary *mdic = [[NSMutableDictionary alloc] initWithDictionary:[NSDictionary dictionaryWithContentsOfFile:pathFirstTime]];
NSLog(#"%#", mdic);
Using this code I am trying to get the data from Templates.plist file but I am getting null value in array.
//from plist
NSString *path = [[NSBundle mainBundle] pathForResource:#"Templates" ofType:#"plist"];
NSMutableArray *arry=[[NSMutableArray alloc]initWithContentsOfFile:path];
NSLog(#"arrayArray:::: %#", arry);
This is my plist file:
Also I want to know how can I add more strings to this plist file and delete a string from this plist.
First off you cannot write to anything in you mainBundle. For you to write to you plist you need to copy it to the documents directory. This is done like so:
- (void)createEditableCopyOfIfNeeded
{
// First, test for existence.
BOOL success;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *writablePath = [documentsDirectory stringByAppendingPathComponent:#"Template.plist"];
success = [fileManager fileExistsAtPath:writablePath];
if (success)
return;
// The writable file does not exist, so copy from the bundle to the appropriate location.
NSString *defaultPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"Template.plist"];
success = [fileManager copyItemAtPath:defaultPath toPath:writablePath error:&error];
if (!success)
NSAssert1(0, #"Failed to create writable file with message '%#'.", [error localizedDescription]);
}
So calling this function will check if the file exists in the documents directory. If it doesn't it copies the file to the documents directory. If the file exists it just returns. Next you just need to access the file to be able to read and write to it. To access you just need the path to the documents directory and to add your file name as a path component.
NSString *docDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *filePath = [docDir stringByAppendingPathComponent:#"Template.plist"];
To get the data from the plist:
NSMutableArray *array = [[NSMutableArray alloc] initWithContentsOfFile:filePath];
To write the file back to the documents directory.
[array writeToFile:filePath atomically: YES];
-(NSMutableArray *)start1
{
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *plistPath = [documentsDirectory stringByAppendingPathComponent:#"Templates.plist"];
if ([[NSFileManager defaultManager] fileExistsAtPath:plistPath]){
plistArr = [NSMutableArray arrayWithContentsOfFile: plistPath];
}
else {
plistArr = [[NSMutableArray alloc] init];
}
return plistArr;
}
- (void)createNewRecordWithName:(NSMutableDictionary *)dict
{
plistArr=[self start1];
[plistArr addObject: dict];
//[dict release];
[self writeProductsToFile:plistArr];
}
- (void)writeProductsToFile:(NSMutableArray *)array1 {
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *plistPath = [documentsDirectory stringByAppendingPathComponent:#"Template.plist"];
[array1 writeToFile:plistPath atomically:YES];
}
To get a plist into a mutable array, use this class method:
NSMutableArray *array = [NSMutableArray arrayWithContentsOfFile:path];
Then, add/delete strings from the array. To save the array back to a plist, use:
[array writeToFile:path atomically:YES];
I've found several questions here on the site with people who have a similar problem, but I'm still not able to resolve mine. Here's the thing:
I'm making an iOS app that contains two plist files. When the user opens the app for the first time, the application takes care of moving these two files to the Documents directory. I know this code works, since I'm subsequently able to read from each of the files in the Documents directory path. However, I'm not able to write to any of them for apparent unknown reasons. Here is the code I use to write to the first plist file:
+ (void)insertNewElementWith:(NSArray *)objects andKeys:(NSArray *)keys {
NSString *filePath = [self returnPathForFirstPlistFile];
NSMutableDictionary *contentOfFirstPlistFile = [[NSMutableDictionary alloc] initWithContentsOfFile:filePath];
NSDictionary *dictionary = [[NSDictionary alloc] initWithObjects:objects forKeys:keys];
[contentOfFirstPlistFile setObject:dictionary forKey:[NSNumber numberWithInt:[contentOfFirstPlistFile count]]];
[contentOfFirstPlistFile writeToFile:filePath atomically:YES];
[dictionary release];
}
returnPathForFirstPlistFile does work, since contentOfFirstPlistFile contains { } rather than null. Can anyone explain to me, though, why it keeps returning { }, even though the above method has been called several times.
Update
Here is the code I use to place the files in the Documents directory. placePlistsInDocumentsDirectory is only called when the user logs in through the app, so this only happens once.
+ (NSString *)returnPathForFirstPlistFile {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:#"First.plist"];
return filePath;
}
+ (NSString *)returnPathForSecondPlistFile {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSLog(#"%#", [paths objectAtIndex:0]);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:#"Second.plist"];
return filePath;
}
+ (void)placePlistsInDocumentsDirectory {
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *firstPlistPath = [self returnPathForFirstPlistFile];
NSString *secondPlistPath = [self returnPathForSecondPlistFile];
if (![fileManager fileExistsAtPath:firstPlistPath]) {
NSError *error;
NSString *bundle = [[NSBundle mainBundle] pathForResource:#"First" ofType:#"plist"];
[fileManager copyItemAtPath:bundle toPath:firstPlistPath error:&error];
}
if (![fileManager fileExistsAtPath:secondPlistPath]) {
NSError *error;
NSString *bundle = [[NSBundle mainBundle] pathForResource:#"Second" ofType:#"plist"];
[fileManager copyItemAtPath:bundle toPath:secondPlistPath error:&error];
}
}
[NSNumber numberWithInt:[contentOfFirstPlistFile count]]
Gives you an NSNumber object. This is not a valid key for a dictionary, the key has to be an NSString. Use
[NSString stringWithFormat:#"%d",[contentOfFirstPlistFile count]]
Instead. Though, if you are using numbers as keys in a dictionary, why not use an array?
I have attempted to reproduce this issue myself and the only way I could manage it was to use a plist that did not have a dictionary as its root object. This returned a dictionary that was not nil, but did not allow any modifications. This could not then be written back to the file. Looking at some of your earlier questions, you were using an array based plist before, so this may be the issue.
I m able to save the plist file in Simulator but I m not able to save the Plist file in the device. Any suggestion.
I m using
NSString* dictPath = [[NSBundle mainBundle] pathForResource:#"Dictionary" ofType:#"plist"];
NSDictionary * dict = [[NSDictionary alloc] initWithContentsOfFile:dictPath];
to read the files
and
[dict writeToFile:dictPath atomically: YES];
to write to file.
You can not write in to main bundle. You only can read from main bundle. If you want to write an file you need to place it in to the documents directory of your app.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.plist",plistName]];
If you need the plist from the main bundle you can copy it first in to the documents directory then modify it. It is advised to have a check to ensure it is copied only once.
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.plist",plistName]];
NSFileManager *fileManager = [NSFileManager defaultManager];
if (![fileManager fileExistsAtPath: path]){
NSLog(#"File don't exists at path %#", path);
NSString *plistPathBundle = [[NSBundle mainBundle] pathForResource:plistName ofType:#"plist"];
[fileManager copyItemAtPath:plistPathBundle toPath: path error:&error];
}else{
NSLog(#"File exists at path:%#", path);
}
Generally you would store these in ~/Documents or in ~/Library depending on the file. The question What is the documents directory (NSDocumentDirectory)? includes the documentation links and sample code you need to understand this.
You need to save the plist in Documents directory
to write
NSString *mainBundlePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *dictPath = [mainBundlePath stringByAppendingPathComponent:#"Dictionary"];
NSDictionary * dict = ...; //Construct your dictionary
[dict writeToFile:dictPath atomically: YES];
to read
NSDictionary * dict = [[NSDictionary alloc] initWithContentsOfFile:dictPath];