iOS Persistent data----(a series of ways to save data

Source: Internet
Author: User

There are three different mechanisms for persisting data to the iOS file system: Attribute list, object archive, embedded database SQLite3 (there are other ways to use traditional C

IO functions read or write data, or can use cocoa's low-level file management tools) each application supports three folders documents, libraries and TMP.  The application stores its data in documents, except for Nsuserdefaults-based preferences, which are stored in the Library/preferences folder, and does not back up files in/tmp when the iOS device synchronizes. 1. The following statement will return to the documents directory NSString *path = [Nssearchpathfordirectoriesindomains (nsdocumentdirectory, Nsuserdomainmask, YES ) objectatindex:0] We can create a file name by appending a string to the end of the path to perform a read or write operation.      NSString *filename = [Path stringbyappendingpathcomponent:@ "test.txt"]; When the above sentence ends, the filename will contain the full path to the Test.txt file, which is located in the application's documents directory, and we can use filename to create a read and write file. 2.  It is convenient to obtain a reference to the corresponding application temp directory, NSString *tmppath = Nstemporarydirectory (); 3, below is the basic code to write an array to the file, (attribute list) Wiritetofile nsstring *str = @ "abc";
NSString *astr = @ "EFG";
Nsarray *array = [Nsarray arraywithobjects:str, Astr, nil];

Save
Nsarray *paths = Nssearchpathfordirectoriesindomains (NSDocumentDirectory, Nsuserdomainmask, YES);
NSString *documentsdirectory = [Paths objectatindex:0];
if (!documentsdirectory) {
NSLog (@ "Documents directory not found!");
}
NSString *appfile = [documentsdirectory stringbyappendingpathcomponent:@ "Savedatas.plist"];
[[Nsarray Arraywithobjects:array,nil] Writetofile:appfile Atomically:no];


Load
if ([[[Nsfilemanager Defaultmanager] fileexistsatpath:appfile])
Self. Savedataarray = [Nsmutablearray arraywithcontentsoffile:appfile];
Else
Self. Savedataarray = [Nsmutablearray arraywithcontentsoffile:[[nsbundle mainbundle] pathforresource:@ "Savedatas" ofType:@ "Plist"];
Nsarray *strarray = [self. Savedataarray objectatindex:0];

str = [Strarray objectatindex:0];
ASTR = [Strarray objectatindex:1]; 4. Archive example (nskeyedarchiver) NSString *str = @ "abc";
NSString *astr = @ "EFG";
Nsarray *array = [Nsarray arraywithobjects:str, Astr, nil];

Save
NSString *path = [Nssearchpathfordirectoriesindomains (nsdocumentdirectory, Nsuserdomainmask, YES) objectAtIndex:0]; NSString *filename = [Path stringbyappendingpathcomponent:@ "test"];
[Nskeyedarchiver Archiverootobject:array Tofile:filename];

str = @ "a";
Astr = @ "";

Load
Nsarray *arr = [Nskeyedunarchiver unarchiveobjectwithfile:filename];
str = [arr objectatindex:0];
Astr = [arr objectatindex:1];

NSLog (@ "str:%@", str);
NSLog (@ "astr:%@", astr); 5. Example (nsuserdefaults) NSString *str = @ "abc";
NSString *astr = @ "EFG";
Nsarray *array = [Nsarray arraywithobjects:str, Astr, nil];

Save
Nsuserdefaults *savedefaults = [Nsuserdefaults standarduserdefaults];
[Savedefaults setobject:array forkey:@ "Savekey"];

str = @ "a";
Astr = @ "";

Load
Array = [Savedefaults objectforkey:@ "Savekey"];
str = [Array objectatindex:0];
ASTR = [Array objectatindex:1];
NSLog (@ "str:%@", str);
NSLog (@ "astr:%@", astr); 6. Here are two convenient ways to store and read data from a forum. The following:-(BOOL) Writeapplicationdata: (nsdictionary *) data writefilename: (NSString *) fileName
{
Nsarray *paths = Nssearchpathfordirectoriesindomains (NSDocumentDirectory, Nsuserdomainmask, YES);
NSString *documentsdirectory = [Paths objectatindex:0];
if (!documentsdirectory) {
NSLog (@ "Documents directory not found!");
return NO;
}
NSString *appfile = [Documentsdirectory stringbyappendingpathcomponent:filename];
return ([Data writetofile:appfile atomically:yes]);
}

-(ID) Readapplicationdata: (NSString *) fileName
{
Nsarray *paths = Nssearchpathfordirectoriesindomains (NSDocumentDirectory, Nsuserdomainmask, YES);
NSString *documentsdirectory = [Paths objectatindex:0];
NSString *appfile = [Documentsdirectory stringbyappendingpathcomponent:filename];
Nsdictionary *mydata = [[[Nsdictionary alloc] initwithcontentsoffile:appfile] autorelease];
return myData;
}  7. The simplest way to save a picture downloaded from the network to a local ~//save the picture to Local + (void) saveimagetolocal: (uiimage*) Image Keys: (nsstring*) Key {     nsuserdefaults* preferences = [Nsuserdefaults standarduserdefaults];     //[preferences persistentdomainforname:localpath];    [preferences SetObject: Uiimagepngrepresentation (image) Forkey:key];}  //whether there is a relevant picture + (BOOL) Localhaveimage: (nsstring*) key {    nsuserdefaults* preferences = [ Nsuserdefaults standarduserdefaults];    //[preferences Persistentdomainforname:localpath];     nsdata* imageData = [Preferences objectforkey:key];    if (ImageData) {         return yes;    }     return NO;}  //get image from local + (uiimage*) getimagefromlocal: (nsstring*) key {    nsuserdefaults* preferences = [Nsuserdefaults standarduserdefaults];    [Preferences persistentdomainforname:localpath];    nsdata* imageData = [Preferences objectforkey:key];    uiimage* image;    if (imageData) {         image = [UIImage imagewithdata:imagedata];    }     else {        nslog (@ "not getting pictures from local");     }    return image;}  8. This is a piece of code shared by the foreigner, save the photo, very simple, hehe  

Parameter description:
NSData to retrieve the image from the URL
nsdocumentdirectory to find Document folder ' s Path
uiimagepngrepresentation to save it as PNG
uiimagejpegrepresentation to save it as JPEG

Code:

NSLog (@ "Downloading ...");
Get an image from the URL below
UIImage *image = [[UIImage alloc] initwithdata:[nsdata datawithcontentsofurl:[nsurl urlwithstring:@ "/http/ Www.objectgraph.com/images/og_logo.png "]];

NSLog (@ "%f,%f", image.size.width,image.size.height);

Let's save the file into Document folder.
You can also the change this to your desktop for testing. (e.g./users/kiichi/desktop/)
NSString *desktopdir = @ "/users/kiichi/desktop";

NSString *docdir = [Nssearchpathfordirectoriesindomains (nsdocumentdirectory, Nsuserdomainmask, YES) objectAtIndex:0] ;

If you go to the folder below, you'll find those pictures
NSLog (@ "%@", Docdir);

NSLog (@ "Saving png");
NSString *pngfilepath = [NSString stringwithformat:@ "%@/test.png", Docdir];
NSData *data1 = [NSData datawithdata:uiimagepngrepresentation (image)];
[Data1 Writetofile:pngfilepath Atomically:yes];

NSLog (@ "Saving jpeg");
NSString *jpegfilepath = [NSString stringwithformat:@ "%@/test.jpeg", Docdir];
NSData *data2 = [NSData datawithdata:uiimagejpegrepresentation (Image, 1.0f)];//1.0f = 100% Quality
[Data2 Writetofile:jpegfilepath Atomically:yes];

NSLog (@ "Saving image done");

[Image release];

iOS Persistent data----(a series of ways to save data

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.