SoFunction
Updated on 2025-04-09

Detailed explanation of four ways to save data in IOS

During iOS development, no matter what application you are doing, you will encounter data storage problems. Saving data locally can make the program run smoother without disgusting chrysanthemum shapes, making the user experience better. Here is a description of how to save data:

Data is stored in the form of archives. The data object needs to comply with the NSCoding protocol, and the corresponding classes of the object must provide the encodeWithCoder: and initWithCoder: methods. The former method tells the system how to encode objects, while the latter method tells the system how to decode objects. For example, archive and save Possession object.

Define Possession:

@interface Possession:NSObject<NSCoding>{//Compliance with the NSCoding protocol
    NSString *name;//Type to be archived

}

@implementation Possession

-(void)encodeWithCoder:(NSCoder *)aCoder{

      [aCoder encodeObject:name forKey:@"name"];


}
-(void)initWithCoder:(NSCoder *)aDecoder{

      name=[[aDeCoder decodeObjectforKey:@"name"] retain];
}

Archive operation:

If you save the Possession object allPossession archive, you only need the method of the NSCoder subclass NSKeyedArchiver archiveRootObject:toFile:.

NSString *path = [self possessionArchivePath];

[NSKeyedArchiver archiveRootObject:allPossessions toFile: path ]

Decompression operation:

Also call the method of the NSCoder subclass NSKeyedArchiver unarchiveRootObject:toFile:

allPossessions = [[NSKeyedUnarchiver unarchiveObjectWithFile:path] retain];

Disadvantages: The data is saved in the form of archives, and can only be archived and saved at one time and decompressed at one time. Therefore, it can only be used for small amounts of data, and it is relatively clumsy to operate on data. That is, if you want to change a small part of the data, you still need to decompress the entire data or archive the entire data.

Used to save application settings and properties and user-saved data. The data still exists after the user opens the program again or boots it. The data types that NSUserDefaults can store include: NSData, NSString, NSNumber, NSDate, NSArray, and NSDictionary. If you want to store other types, you need to convert them to the previous type before you can store them with NSUserDefaults. The specific implementation is:

Save data:

NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
 NSString *name =@”default string“;
 [defaults setObject:firstName forKey:@"name"];
  //Get UIImage instance
UIImage *image=[[UIImage alloc]initWithContentsOfFile:@""];

 NSData *imageData = UIImageJPEGRepresentation(image, 100);//Convert UIImage object to NSData
 [defaults synchronize];//Use synchronize method to persist data to standardUserDefaults database

Read data:

NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
 NSString *name = [defaults objectForKey:@"name"];//Fetch name according to the key value NSData *imageData = [defaults dataForKey:@"image"];
 UIImage *Image = [UIImage imageWithData:imageData];//NSDataConvert toUIImage

3. Write method: permanently saved on disk. The specific method is:

Step 1: Obtain the path to which the file is about to be saved:

NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES);//Use the C function NSSearchPathForDirectoriesInDomains to get the full path of the directory in the sandbox.  This function has three parameters: directory type, he domain mask, and boolean value.  The Boolean value indicates whether it is necessary to pass the ~ extension path.  And the first parameter is unchanged, that is, NSSearchPathDirectory.  The last two parameters in iOS are also unchanged, namely: NSUserDomainMask and YES.NSString *ourDocumentPath =[documentPaths objectAtIndex:0];

Another way is to use the NSHomeDirectory function to get the path to the sandbox. The specific usage is:

NSString *sandboxPath = NSHomeDirectory();
 // Once you have the full sandbox path, you can create a path from it, but you cannot write files on this file layer of sandbox or create directories. Instead, you should create a new writable directory based on this, such as Documents, Library or temp.NSString *documentPath = [sandboxPath
       stringByAppendingPathComponent:@"Documents"];//Add Documents to the sandbox path, the specific reasons have been analyzed before!

The difference between the two is that using NSSearchPathForDirectoriesInDomains is safer than adding Document behind NSHomeDirectory. Because the file directory may change on the system sent in the future.

Step 2: Generate the file under this path:

NSString *FileName=[documentDirectory stringByAppendingPathComponent:fileName];//fileNameIt is the file name that saves the file

Step 3: Write data into the file:

[data writeToFile:FileName atomically:YES];//WillNSDataType objectdataWrite to a file,The file name isFileName

Finally: Read the data from the file:

NSData data=[NSData dataWithContentsOfFile:FileName options:0 error:NULL];//fromFileNameRead out data

4. SQLite:Use SQLite database to store data. As a small and medium-sized database, SQLite is relatively complicated in application of ios compared to the first three saving methods. Let’s do it step by step!

Step 1: You need to add SQLite-related libraries and header files: Under Build Phases in the project file, find Link Binary Library(ies) and add libsqlite3. (I don’t know the difference from the former for the time being, the two should be similar); add the header file in the project file or the source file #import "/usr/include/"

Step 2: Get started with SQLite:

NSArray *documentsPaths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask , YES);
 NSString *databaseFilePath=[[documentsPaths objectAtIndex:0] stringByAppendingPathComponent:@"mydb"];
 //The above two sentences are already familiar!//Open the databaseif (sqlite3_open([databaseFilePath UTF8String], &database)==SQLITE_OK) { 
     NSLog(@"sqlite dadabase is opened."); 
 }
 else{ return;}//If you fail to open, return

On the premise that the database has no tables, then start building tables!

char *error; 
 const char *createSql="create table(id integer primary key autoincrement, name text)";
 if (sqlite3_exec(database, createSql, NULL, NULL, &error)==SQLITE_OK) { 
     NSLog(@"create table is ok."); 
 }
 else
 {
    NSLog(@"error: %s",error);
    sqlite3_free(error);//Empty the error string after each use, and provide it to the next use} 

After the table is completed, the record is inserted:

const char *insertSql="insert into a person (name) values(‘gg')"; 
if (sqlite3_exec(database, insertSql, NULL, NULL, &error)==SQLITE_OK) { 
     NSLog(@"insert operation is ok."); 
 }

 else
 {
    NSLog(@"error: %s",error);
    sqlite3_free(error);//Empty the error string after each use, and provide it to the next use} 

Next, query the record:

const char *selectSql="select id,name from a person"; 
 sqlite3_stmt *statement; 
 if (sqlite3_prepare_v2(database,selectSql, -1, &statement, nil)==SQLITE_OK) { 
     NSLog(@"select operation is ok."); 
 }
 else
 {
    NSLog(@"error: %s",error);
    sqlite3_free(error);
 } 
 while(sqlite3_step(statement)==SQLITE_ROW) { 
 int _id=sqlite3_column_int(statement, 0); 
 NSString *name=(char*)sqlite3_column_text(statement, 1); 
 NSLog(@"row>>id %i, name %s",_id,name); 
 }
 sqlite3_finalize(statement);

Finally, close the database:

sqlite3_close(database); 

Note: When writing to the database, the string can be char-type, and the char type can be taken from the database. When the char type has Chinese characters, garbled code will appear. This is because the database uses ascII encoding by default. Therefore, in order to correctly retrieve Chinese from the database, you need to use NSString to receive the strings retrieved from the database.

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.