In UserDefault file I have six fields. I want to persist two field always and reset four other field in some scenario. What is best approach to handle this?
If your want the four field to reset with their default values.
And the default value may be an empty string ,
#define KDefault #""
NSUserDefaults *standardUserDefaults = [NSUserDefaults standardUserDefaults];
if (standardUserDefaults)
{
[standardUserDefaults setObject:KDefault forKey:#"first"];
[standardUserDefaults setObject:KDefault forKey:#"two"];
[standardUserDefaults setObject:KDefault forKey:#"third"];
[standardUserDefaults setObject:KDefault forKey:#"four"];
[standardUserDefaults synchronize];
}
Edited:
For removing field rather than resetting: Use the below
[standardUserDefaults removeObjectForKey:#"first"];
[standardUserDefaults removeObjectForKey:#"two"];
[standardUserDefaults removeObjectForKey:#"third"];
[standardUserDefaults removeObjectForKey:#"four"];
[standardUserDefaults synchronize];
.you can use NSFileManager..sample code
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); //1
NSString *documentsDirectory = [paths objectAtIndex:0]; //2
NSString *path = [documentsDirectory stringByAppendingPathComponent:#"user.plist"]; //3
NSFileManager *fileManager = [NSFileManager defaultManager];
if (![fileManager fileExistsAtPath: path]) //4
{
NSString *bundle = [[NSBundle mainBundle] pathForResource:#"user" ofType:#"plist"]; //5
[fileManager copyItemAtPath:bundle toPath: path error:&error]; //6
}
NSMutableDictionary *savedStock = [[NSMutableDictionary alloc] initWithContentsOfFile: path];
//load from savedStock example int value
NSString* userName;
NSString* password;
NSString* pin;
userName = [savedStock objectForKey:#"name"];
password = [savedStock objectForKey:#"password"];
if([userName isEqualToString:#"some"] && [userName isEqualToString:#"some"] && [pin isEqualToString:#"some"])
{
[self setAdd];
}
else
{
[self pinAdd];
}
Related
How can I store NSMutableArray of custom objects?
I have this code for loading and saving files:
- (NSMutableArray *)loadDataFromFile:(NSString *)fileName {
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docDir = [paths objectAtIndex:0];
NSString *path = [docDir stringByAppendingPathComponent:fileName];
NSFileManager *fileMgr = [NSFileManager defaultManager];
if (![fileMgr fileExistsAtPath:path]) {
NSArray *fileArray = [fileName componentsSeparatedByString:#"."];
NSString *name = [fileArray objectAtIndex:0];
NSString *ext = [fileArray objectAtIndex:1];
NSString *bundle = [[NSBundle mainBundle] pathForResource:name ofType:ext];
[fileMgr copyItemAtPath:bundle toPath:path error:&error];
}
NSMutableArray *data = [[NSMutableArray alloc] initWithContentsOfFile:path];
return data;
}
- (void)saveData:(NSMutableArray *)arrayData toFile:(NSString *)filename forKey:(NSString *)key {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docDir = [paths objectAtIndex:0];
NSString *path = [docDir stringByAppendingPathComponent:filename];
[arrayData writeToFile: path atomically:YES];
NSLog(#"%#", arrayData);
}
But when I used data.plist as filename, it didn't work because NSLog(#"%#", arrayData); returns list custom object adresses:
"AreaTableRecord: 0x76a7ef0"
This custom object is inserted to array using this code:
AreaTableRecord *area=[[AreaTableRecord alloc] init];
area.title=title;
area.lastScore=0;
area.vocabulary=[[NSMutableArray alloc] init];
[self.areas addObject:area];
How could I store NSMutableArray self.areas that contains custom objects AreaTableRecord?
and
What file format shloud I use to store this data? (it seems to me that plist is not working in this case)
You are only able to store primitive data types in NSDefaults or a plist. In order to work around this you can either choose to store your information in a database....or encode your objects as byte streams and then save them into a file.
Take a look at this thread. It details how to go about encoding your objects.
Basically you need to add these methods to your custom class:
- (void)encodeWithCoder:(NSCoder *)encoder
{
//Encode properties, other class variables, etc
[encoder encodeObject:self.question forKey:#\"question\"];
[encoder encodeObject:self.categoryName forKey:#\"category\"];
[encoder encodeObject:self.subCategoryName forKey:#\"subcategory\"];
}
- (id)initWithCoder:(NSCoder *)decoder
{
self = [super init];
if( self != nil )
{
//decode properties, other class vars
self.question = [decoder decodeObjectForKey:#\"question\"];
self.categoryName = [decoder decodeObjectForKey:#\"category\"];
self.subCategoryName = [decoder decodeObjectForKey:#\"subcategory\"];
}
return self;
}
And then in order to use them you make calls as such:
For setting:
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSData *myEncodedObject = [NSKeyedArchiver archivedDataWithRootObject:obj];
[defaults setObject:myEncodedObject forKey:#\"myEncodedObjectKey\"];
For retrieving:
NSUserDefaults defaults = [NSUserDefaults standardUserDefaults];
NSData *myEncodedObject = [defaults objectForKey: key];
MyCustomObject* obj = (MyCustomObject*)[NSKeyedUnarchiver unarchiveObjectWithData: myEncodedObject];
i am new to iPhone developer, i am creating ePub reader for reading ePub files.
I have plist in my iphone app and I want to read and write data to my .plist file, in which i am facing problem.
here is my code snippet,
Logic: first i am downloading an ePub file, .ePub file will be downloaded to this path
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;
NSLog(#"basePath=%#",basePath);
output :-
=/Users/krunal/Library/Application Support/iPhone Simulator/5.1/Applications/6B7FCD58-EDF9-44F4-8B33-5F3542536F92/Documents
now, i want to write name of Downloaded .ePubfile into file into my .plist
code:
NSMutableDictionary *data = [[NSMutableDictionary alloc] initWithContentsOfFile: basePath];
[data setObject:[NSNumber numberWithInt:value] forKey:#"value"];
[data writeToFile: plistPath atomically:YES];
[data release];
i tried this, but i am unable to write in my .plist file.
Any Help Will be Appriciated.
Thanks In Advance !!
Did you mean:
NSMutableDictionary *data = [[NSMutableDictionary alloc] initWithContentsOfFile: plistPath];
?
untested code follows:
Step 1: Copy the file to it's folder.
NSError *error1;
BOOL resourcesAlreadyInDocumentsDirectory;
BOOL copied1;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath1 = [documentsDirectory stringByAppendingString:#"/epub.plist"];
resourcesAlreadyInDocumentsDirectory = [fileManager fileExistsAtPath:filePath1];
if(resourcesAlreadyInDocumentsDirectory == YES) {
} else {
NSString *path1 = [[[NSBundle mainBundle] resourcePath] stringByAppendingFormat:#"/epub.plist"];
copied1 = [fileManager copyItemAtPath:path1 toPath:filePath1 error:&error1];
if (!copied1) {
NSAssert1(0, #"Failed to copy epub.plist. Error %#", [error1 localizedDescription]);
}
}
Step 2:Open it
NSMutableDictionary* dict = [[NSMutableDictionary alloc] initWithContentsOfFile:filePath1];
Step 3:Write data to it
[dict setObject:[NSNumber numberWithInt:value] forKey:#"value"];
[dict writeToFile:path atomically:YES];
NSMutableDictionary *data = [[NSMutableDictionary alloc] initWithContentsOfFile: basePath];
data is nil here, you should init it with:
NSMutableDictionary *data = [[NSMutableDictionary alloc] init];
Edited my answer to be more clear:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;
if ( basePath == nil ) {
return
}
NSMutableDictionary *data = [[NSMutableDictionary alloc] init];
[data setObject:[NSNumber numberWithInt:value] forKey:#"value"];
NSString *plistPath = [NSString stringWithFormat:#"%#/name.plist", basePath];
[data writeToFile: plistPath atomically:YES];
[data release];
It is easer for you to use NSUserDefault, you data will be saved to a plist file as following code:
- (void)setOverviewGroupInstrument:(BOOL)isGroupded {
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
[prefs setObject:[Your array] forKey:[Your Key]];
[prefs synchronize];
}
Then you can read by:
- (NSMutableArray*)getOverviewInstrumentList {
return [prefs objectForKey:[Your Key]];
}
I am new in iphone, i want to save NSMutableArray data into plist file my Code is:
NSArray *array = [[NSArray alloc] initWithArray:self.artistDetailsArray];
[self.artistDetailsArray writeToFile:self.path atomically:YES];
but it shows 0 element in my plist path. please any help me.
Thanks in advance:
following is my code to store the data into plist and NSUserDefault.
none of them is working for NSMutableArray/NSArray but working for NSString. IS there any max size limit to store in plist or UserDefault??
NSMutableArray contains only text/ set of NSDictionary.
please suggest me.
- (void)initialiseDataFromLocalStorage
{
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
self.path = [documentsDirectory stringByAppendingPathComponent:#"saveLogin.plist"];
if ([fileManager fileExistsAtPath:self.path] == NO) {
NSString *pathToDefaultPlist = [[NSBundle mainBundle] pathForResource:#"saveLogin" ofType:#"plist"];
if ([fileManager copyItemAtPath:pathToDefaultPlist toPath:self.path error:&error] == NO) {
NSAssert1(0,#"Failed with error '%#'.", [error localizedDescription]);
}
}
// To get stored value from .plist
NSDictionary *dict = [[NSDictionary alloc]initWithContentsOfFile:self.path];
self.ResumedataDictionary = [[NSMutableDictionary alloc]initWithDictionary:dict];
[dict release];
self.artistDetailsArray = [[NSMutableArray alloc] initWithArray:[self.ResumedataDictionary objectForKey:#"artistDetailsDict"]];
// To get stored value from NSUserDefault
NSUserDefaults *fetchData = [NSUserDefaults standardUserDefaults];
self.artistDetailsArray = [fetchData objectForKey:#"artistDetailsDict"];
}
-(void)saveDataToLocalStorage
{
// To store value into .plist
NSArray *array = [[NSArray alloc] initWithArray:self.artistDetailsArray];
[ResumedataDictionary setObject:array forKey:#"artistDetailsDict"];
[ResumedataDictionary writeToFile:self.path atomically:YES];
// To store value into NSUserDefault
NSUserDefaults *fetchData = [NSUserDefaults standardUserDefaults];
[fetchData setObject:self.artistDetailsArray forKey:#"artistDetailsDict"];
}
NSMutableArray *array=[[NSMutableArray alloc] init];
[array addObject:#"test"];
[array writeToFile:#"/Users/parag/test.plist" atomically:YES];
[array release];
or
NSMutableArray *array=[[NSMutableArray alloc] init];
[array addObject:#"test121"];
id plist = [NSPropertyListSerialization dataFromPropertyList:(id)array format:NSPropertyListXMLFormat_v1_0 errorDescription:#error];
[plist writeToFile:#"/Users/parag/test.plist" atomically:YES];
Take a look at Creating Property Lists Programmatically
look at this code which creates path to plist in documents directory:
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); //1
NSString *documentsDirectory = [paths objectAtIndex:0]; //2
NSString *path = [documentsDirectory stringByAppendingPathComponent:#"data.plist"]; //3
NSFileManager *fileManager = [NSFileManager defaultManager];
if (![fileManager fileExistsAtPath: path]) //4
{
NSString *bundle = [[NSBundle mainBundle] pathForResource:#”data” ofType:#”plist”]; //5
[fileManager copyItemAtPath:bundle toPath: path error:&error]; //6
}
1) Create a list of paths.
2) Get a path to your documents directory from the list.
3) Create a full file path.
4) Check if file exists.
5) Get a path to your plist created before in bundle directory (by Xcode).
6) Copy this plist to your documents directory.
next read data:
NSMutableDictionary *savedStock = [[NSMutableDictionary alloc] initWithContentsOfFile: path];
//load from savedStock example int value
int value;
value = [[savedStock objectForKey:#"value"] intValue];
[savedStock release];
write data:
NSMutableDictionary *data = [[NSMutableDictionary alloc] initWithContentsOfFile: path];
//here add elements to data file and write data to file
int value = 5;
[data setObject:[NSNumber numberWithInt:value] forKey:#”value”];
[data writeToFile: path atomically:YES];
[data release]
You can use property lists (NSPropertyListSerialization or writeToFile: way).
But be sure your array contains valid property list objects only (NSString, NSNumber, NSData, NSArray, or NSDictionary objects) and NSDictionary has only NSString keys. Custom (complex) objects have to be represented as dictionaries.
Or you should use approach with archives http://developer.apple.com/library/ios/#documentation/Cocoa/Conceptual/Archiving/Archiving.html through NSCoding protocol.
Nice guide is here http://cocoadevcentral.com/articles/000084.php
NSData *serializedData;
NSString *error;
serializedData = [NSPropertyListSerialization dataFromPropertyList:YourArray(You can use dictionaries.strings..and others too)
format:NSPropertyListXMLFormat_v1_0 errorDescription:&error];
if (serializedData) {
// Serialization was successful, write the data to the file system // Get an array of paths.
NSArray *documentDirectoryPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docDir = [NSString stringWithFormat:#”%#/serialized.xml”,
[documentDirectoryPath objectAtIndex:0]];
[serializedData writeToFile:docDir atomically:YES];
}
else {
// An error has occurred, log it
NSLog(#”Error: %#”,error); }
}
Iam developing one applciation.In that application i used the both imageview and textview.And iam used the NSUserdefaults for storing the imageview image value and textview text value.But when iam going to another page and coming to main page only imageview image data will be available in nsuserdefaults,textview text data is not avialable.So please tell me how to get the textview text data also by using nsuserdefaults
You should check your Key for spelling mistakes. By the way, just for reference,
Methods of saving images to NSUserDefaults:
Number 1: Saving and retrieving image directly:
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
NSData *imageData = [NSKeyedArchiver archivedDataWithRootObject:imageView.image];
[userDefaults setObject:imageData forKey:#"Image"];
//Retrieving
UIImage *image = (UIImage*)[NSKeyedUnarchiver unarchiveObjectWithData:[userDefaults objectForKey:#"Image"]];
Number 2: Saving the image in documents directory and saving its path in NSUserDefaults:
//Saving
//Obtain the path for Documents Directory
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
//Append Image name to the path
NSString *imagePath = [[documentsDirectory stringByAppendingPathComponent:#"Image"] retain];
//Creating a file at this path
NSFileManager *fileManager = [NSFileManager defaultManager];
BOOL ok = [fileManager createFileAtPath:dataFilePath contents:nil attributes:nil];
if (!ok) {
NSLog(#"Error creating file %#", dataFilePath);
}
else {
//Writing image to the created file
NSFileHandle *myFileHandle = [NSFileHandle fileHandleForWritingAtPath:imagePath];
[myFileHandle writeData:UIImageJPEGRepresentation(imageView.image, 1.0)];
[myFileHandle closeFile];
}
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
if (userDefaults) {
[userDefaults setObject:imagePath forKey:#"ImagePath"];
}
//Retrieving
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
NSString *imagePath = [userDefaults objectForKey:#"ImagePath"];
NSFileHandle* fileHandle = [NSFileHandle fileHandleForReadingAtPath:dataFilePath];
UIImage* loadedImage = [UIImage imageWithData:[fileHandle readDataToEndOfFile]];
Method of saving text to NSUserDefaults:
//Saving
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
[userDefaults setValue:textView.text forKey:#"Text"];
//Retrieving
textView.text = [userDefaults valueForKey:#"Text"];
How do I save an NSString as a .txt file on my apps local documents directory (UTF-8)?
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents directory
NSError *error;
BOOL succeed = [myString writeToFile:[documentsDirectory stringByAppendingPathComponent:#"myfile.txt"]
atomically:YES encoding:NSUTF8StringEncoding error:&error];
if (!succeed){
// Handle error here
}
Something like this:
NSString *homeDirectory;
homeDirectory = NSHomeDirectory(); // Get app's home directory - you could check for a folder here too.
BOOL isWriteable = [[NSFileManager defaultManager] isWritableFileAtPath: homeDirectory]; //Check file path is writealbe
// You can now add a file name to your path and the create the initial empty file
[[NSFileManager defaultManager] createFileAtPath:newFilePath contents:nil attributes:nil];
// Then as a you have an NSString you could simple use the writeFile: method
NSString *yourStringOfData;
[yourStringOfData writeToFile: newFilePath atomically: YES];
He is how to save NSString into Documents folder. Saving other types of data can be also realized that way.
- (void)saveStringToDocuments:(NSString *)stringToSave {
NSString *documentsFolder = [NSHomeDirectory() stringByAppendingPathComponent:#"Documents"];
NSString *fileName = [NSString stringWithString:#"savedString.txt"];
NSString *path = [documentsFolder stringByAppendingPathComponent:fileName];
[[NSFileManager defaultManager] createFileAtPath:path contents:[stringToSave dataUsingEncoding:NSUTF8StringEncoding] attributes:nil];
}
you could use NSUserDefaults
Saving:
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
[prefs setObject:#"TextToSave" forKey:#"keyToLookupString"];
Reading:
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
NSString *myString = [prefs stringForKey:#"keyToLookupString"];
I was using this method to save some base64 encoded image data to the disk. When opening the text file on my computer I kept having trouble reading the data because of some line breaks and returns being added automatically.
The following code fixes this issue:
myString = [myString stringByReplacingOccurrencesOfString:#"\n" withString:#""];
myString = [myString stringByReplacingOccurrencesOfString:#"\r" withString:#""];
// write string to disk