IOS object archive database storage

Source: Internet
Author: User

In iOS development, databases are saved normally.

However, if the objects to be saved are not all of the basic data types or are not supported by the database, is it instantly petrochemical.

For example:

A message object contains an attatchment object. It is required that each message be saved. It is normal to select the SQLite database to save it (I use it anyway ), however, SQLite does not support the attatchment type. How can this problem be solved ???

Method 1:

Putting all attributes in attatchment into message is no problem. It is also a good method, but is it a little far-fetched?

Method 2:

The method I want to introduce today is to archive objects into nsdata and store them. When the query is made, it will be OK when the file is Unarchived.

Give Code directly (database storage uses a third-party database fmdb ):


Source code


The attatchment entity class is provided (it is not defined in detail for a simple test ):

//
// Attatchment. h
// Demo
//

# Import <Foundation/Foundation. h>

@ Interface attatchment: nsobject <nscoding> {
Nsstring * _ localpath;
}
@ Property (nonatomic, copy) nsstring * localpath;
@ End

//
// Attatchment. m
// Demo
//

# Import "attatchment. H"

@ Implementation attatchment
@ Synthesize localpath = _ localpath;
-(Void) encodewithcoder :( nscoder *) ACO {
[Ecoder encodeobject: _ localpath forkey: @ "localpath"];
}

-(ID) initwithcoder :( nscoder *) adecoder {
Self = [Super init];
If (self! = Nil ){
_ Localpath = [[adecoder decodeobjectforkey: @ "localpath"] retain];
}
Return self;
}
@ End

Given the message entity (also a simple definition ):

//
// Message. h
// Demo
//

# Import <Foundation/Foundation. h>
# Import "attatchment. H"

@ Interface message: nsobject {
Nsstring * _ messageid;
Attatchment * _ ATT;
}
@ Property (nonatomic, copy) nsstring * messageid;
@ Property (nonatomic, retain) attatchment * ATT;
@ End

//
// Message. m
// Demo
//

# Import "message. H"

@ Implementation message
@ Synthesize messageid = _ messageid;
@ Synthesize ATT = _ ATT;
@ End

In this way, the two entities are defined.

The important process is storage:

Here is a self-written dbmanager (rough writing, sorry !)

//
// Dbmanager. h
// Fetionhd
//

# Import <Foundation/Foundation. h>
# Import "fmdatabase. H"
# Import "message. H"

# Define databasepath [[(nssearchpathfordirectoriesindomains (nsdocumentdirectory, nsuserdomainmask, yes) lastobject] stringbyappendingpathcomponent: databasename]
# Define databasename @ "database. SQLite"

@ Interface dbmanager: nsobject

/****/
/**
* @ Brief database object Singleton Method
*
* @ Return returns the fmdatebase database operation object.
*/
+ (Fmdatabase *) createdatabase;

/**
* @ Brief shut down the database
*/
+ (Void) closedatabase;

/**
* @ Brief clear the database content
*/
+ (Void) deletedatabase;

/**
* @ Brief determine whether the table exists
*
* @ Param tablename indicates
*
* @ Return: whether the creation is successful
*/
+ (Bool) istableexist :( nsstring *) tablename;

/**
* @ Brief create all tables
*
* @ Return
*/
+ (Bool) createtable;
/**
* @ Brief add chatdata. If the primary key already exists, it will be updated.
*
* @ Param chatdata the chatdata to be saved
*
* @ Return indicates whether the file is saved or updated successfully.
*/
+ (Bool) saveorupdatamessage :( message *) chatdata;
+ (Message *) selectmessagebymessageid :( nsstring *) messageid;
@ End

//
// Dbmanager. m
// Fetionhd

# Import <Foundation/Foundation. h>
# Import "dbmanager. H"

# Define debugmethod (...) nslog (@ "in % s, % s [line % d]"), _ pretty_function __,__ file __,__ line __,#__ va_args __)
Static fmdatabase * relational database = nil;
@ Implementation dbmanager

/**
Create a single instance object for the database class
 
**/
// + (Fmdatabase *) createdatabase {
//// Debugmethod ();
// @ Synchronized (Self ){
// If (relational database = nil ){
//
// Restore database = [[fmdatabase databasewithpath: databasepath] retain];
//}
// Return response database;
//}
//}
// This method can achieve thread security, but multiple calls will cause a significant reduction in performance

+ (Fmdatabase *) createdatabase {
Static dispatch_once_t oncetoken;
Dispatch_once (& oncetoken, ^ {
Relational Database = [[fmdatabase databasewithpath: databasepath] retain];
});
Return response database;
}

/**
Determine whether a table exists in the Database
**/
+ (Bool) istableexist :( nsstring *) tablename
{
Fmresultset * rs = [your database executequery: @ "select count (*) as 'Count' from sqlite_master where type = 'table' and name =? ", Tablename];
While ([RS next])
{
// Just print out what we 've got in a number of formats.
Nsinteger COUNT = [RS intforcolumn: @ "count"];
Nslog (@ "% @ isok % d", tablename, count );

If (0 = count)
{
Return no;
}
Else
{
Return yes;
}
}

Return no;
}

/**
Create a table
**/
+ (Bool) createtable {
Debugmethod ();
Nslog (@ "% @", databasepath );
If (1 ){
{
Relational Database = [dbmanager createdatabase];
If ([Restore database open]) {
If (! [Dbmanager istableexist: @ "message_table"]) {
Nsstring * SQL = @ "CREATE TABLE \" message_table \ "(\" message_id \ "text primary key not null check (typeof (\" message_id \ ") = 'text '), \ "ATT \" Blob )";
Nslog (@ "no medicine ");
[Relational database executeupdate: SQL];
}
[Closing database close];
}
}
}
Return yes;
}

/**
Close Database
**/
+ (Void) closedatabase {
If (! [Relational database close]) {
Nslog (@ "database shutdown exception, please check ");
Return;
}
}

/**
Delete Database
**/
+ (Void) deletedatabase {
If (relational database! = Nil ){
// Delete the database table here
}
}

+ (Bool) saveorupdatamessage :( message *) Message
{
Bool isok = no;
Relational Database = [dbmanager createdatabase];
If ([Restore database open]) {
Isok = [relational database executeupdate:
@ "Insert into \" message_table \ "(\" message_id \ ", \" ATT \ ") values (?,?) ", Message. messageid, [nskeyedarchiver archiveddatawithrootobject: Message. ATT];
[Closing database close];
}
Return isok;
}

+ (Message *) selectmessagebymessageid :( nsstring *) messageid
{
Message * m = nil;
Relational Database = [dbmanager createdatabase];
If ([Restore database open]) {
Fmresultset * s = [your database executequery: [nsstring stringwithformat: @ "select * From \" message_table \ "where \" message_id \ "= '% @'", messageid];
If ([s next]) {
M = [[Message alloc] init];
M. messageid = [s stringforcolumn: @ "message_id"];
M. ATT = [nskeyedunarchiver unarchiveobjectwithdata: [s dataforcolumn: @ "ATT"];
}
[Closing database close];
}
Return m;
}
@ End

The rest of the work is to call the @ _ @ interface @_@

-(Ibaction) addaction :( ID) sender {
Message * message = [[Message alloc] init];
Attatchment * ATT = [[attatchment alloc] init];
Message. messageid = @ "11 ";
Message. ATT = ATT;
Att. localpath = @ "a.png ";
[Dbmanager createtable];
[Dbmanager saveorupdatamessage: Message];

[ATT release];

[Message release];

}

-(Ibaction) selectaction :( ID) sender {
Message * message = [dbmanager selectmessagebymessageid: @ "11"];
Nslog (@ "% @", message. Att. localpath );
Nslog (@ "% @", message. messageid );
}

Remember to add the fmdb library and sqlite3 Library to the project. You can try it for unexpected results.

This is my first blog post. Welcome @_@.

Related Article

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.