Runtime arbitrary type model database for easy storage

Source: Internet
Author: User
Tags allkeys stmt

After the code here, I'm slowly explaining my qq:378254160 I have a demo for you to use contact me notes runtime+ database + any model type of course sometimes there are limitations.

Databasehandle.m

#import "DataBasehandle.h"

#import <objc/runtime.h>

#import <sqlite3.h>

Http://www.sjsjw.com/kf_mobile/article/4_17043_17742.asp

@interface Databasehandle ()

@property (nonatomic, copy) NSString *tabelename;

@property (nonatomic, copy) Nsdictionary *dic;

@end

@implementation Databasehandle

/* Get all the properties and property contents of the object */

This method returns a large dictionary with all the non-empty attributes and their Value property being the key value

-(Nsdictionary *) Getallpropertiesandvaulesmodel: (ID) model

{

Nsmutabledictionary *props = [Nsmutabledictionary dictionary];

unsigned int outcount, I;

objc_property_t *properties = Class_copypropertylist ([model class], &outcount);

for (i = 0; i<outcount; i++)

{

objc_property_t property = Properties[i];

Const char* Char_f =property_getname (property);

NSString *propertyname = [NSString stringwithutf8string:char_f];

ID propertyvalue = [model Valueforkey: (NSString *) PropertyName];

/* This statement, which is commented below, is the first statement of the function to get a property with a value that is not NULL I modified it to get all the model genera

Of course the model attribute must all be written in NSString type regardless of the actual type! */

if (PropertyValue) [props setobject:propertyvalue forkey:propertyname];

This will get all the properties of the Model Object!!!! The following code is I modified!

if (PropertyValue = = nil) {

[Props setobject:@ "nil" forkey:propertyname];

}else

{

[Props Setobject:propertyvalue Forkey:propertyname];

}

}

Free (properties);

return props;

}

Static Databasehandle * Sharedatamanager = nil;

This prevents multi-process access to GCD notation!!!!!

+ (Databasehandle *) shareddatabasehandle

{

Static dispatch_once_t once;

Dispatch_once (&once

, ^{

if (Sharedatamanager = = nil)

{

Sharedatamanager = [[Databasehandle alloc] init];

}

});

return sharedatamanager;

}

static Sqlite3 *db = nil;

-(void) opendb

{

You don't have to open it when you're done.

if (db! = nil) return;

Get the name of the Shahe path stitching a file

NSString *document = Nssearchpathfordirectoriesindomains (NSDocumentDirectory, Nsuserdomainmask, YES) [0];

NSString *path = [Document stringbyappendingpathcomponent:[nsstring stringwithformat:@ "/%@", @ "Adress.sqlite"];

NSLog (@ "%@", Path);

Open database Initialize database The static zone is not nil.

int result = Sqlite3_open (path. Utf8string, &db);

if (result = = SQLITE_OK)

{

Open success!

NSLog (@ "open successfully");

}else

{

NSLog (@ "Open failed");

}

}

-(void) closedb

{

int result = Sqlite3_close (db);

if (result = = SQLITE_OK) {

NSLog (@ "close success");

}else

{

NSLog (@ "shutdown failed");

}

}

Create a table based on the name of the table and the model object at run time!

-(void) Createtablename: (NSString *) name model: (ID) model

{

Stitching strings by model

Nsdictionary *dicstart = [self Getallpropertiesandvaulesmodel:model];

This must be done in this way to become an immutable dictionary otherwise, the Order of the table properties is not the same!

Nsdictionary *dic = [Nsdictionary Dictionarywithdictionary:dicstart];

Self.dic = dic;

Self.tabelename = name;

nsmutablestring *str = [nsmutablestring string];

for (id obj in [dic AllKeys])

{

[Str appendformat:@ "%@ text,", obj];

}

NSString *str1 = [str substringtoindex:str.length-1];

SQL statement to create TABLE + table name (field type, ..., field type)

NSString *createstr = [NSString stringwithformat:@ "CREATE TABLE IF not EXISTS%@ (%@)", NAME,STR1];

NSLog (@ "CREATESTR = = =%@", createstr);

First parameter: operation in that database

Second parameter: Represents the SQL statement to execute

Third parameter: Represents the callback function

Fourth parameter: Some parameters of a callback

Fifth parameter: Error message

char *error = NULL;

int result = SQLITE3_EXEC (db, createstr.utf8string, NULL, NULL, &ERROR);

printf ("massage =%s", error);

if (result = = SQLITE_OK)

{

NSLog (@ "Genesis success");

}else

{

NSLog (@ "Failure to create a table");

}

}

Writes the model object to the database based on the name of the currently created table and the run-time model object

-(void) Insertintotablemodel: (ID) model

{

Nsdictionary *dicstart = [self Getallpropertiesandvaulesmodel:model];

Nsdictionary *dic = [Nsdictionary Dictionarywithdictionary:dicstart];

NSString *name = self.tabelename;

nsmutablestring *strkey = [nsmutablestring string];

nsmutablestring *strvalue = [nsmutablestring string];

for (id obj in [dic AllKeys])

{

[Strkey appendformat:@ "%@,", obj];

[strvalue appendformat:@ "'%@ ',", [dic objectforkey:obj];

}

NSString *strkey1 = [Strkey substringtoindex:strkey.length-1];

NSString *strvalue1 = [strvalue substringtoindex:strvalue.length-1];

Insert statement

NSString *insertstr = [NSString stringwithformat:@ "INSERT into%@ (%@) VALUES (%@)", name,strkey1,strvalue1];

First parameter: operation in that database

Second parameter: Represents the SQL statement to execute

Third parameter: Represents the callback function

Fourth parameter: Some parameters of a callback

Fifth parameter: Error message

NSLog (@ "%@", strkey1);

char *message = NULL;

int result = SQLITE3_EXEC (db, insertstr.utf8string, NULL, NULL, &message);

printf ("Massage =======%s", message);

if (result = = SQLITE_OK)

{

NSLog (@ "Insert success");

}else

{

NSLog (@ "Insert failed");

}

}

Deletes a data corresponding to the model object based on the name of the current table and the run-time model Object!

-(void) Deletefromtablemodel: (ID) model

{

Nsdictionary *dicstart = [self Getallpropertiesandvaulesmodel:model];

Nsdictionary *dic = [Nsdictionary Dictionarywithdictionary:dicstart];

NSString *name = self.tabelename;

nsmutablestring *strkey = [nsmutablestring string];

for (id obj in [dic AllKeys])

{

if ([[DiC objectforkey:obj] Iskindofclass:[nsnumber class] | | [[DiC Objectforkey:obj] iskindofclass:[nsstring class]]

{

[Strkey appendformat:@ "%@ = '%@ ' and", Obj,[dic Objectforkey:obj]];

}

}

Get rid of the last four characters

NSString *strnew = [Strkey substringtoindex:strkey.length-4];

NSString *deletestr = [NSString stringwithformat:@ "DELETE from%@ WHERE%@", name,strnew];

char *message = NULL;

int result = SQLITE3_EXEC (db, deletestr.utf8string, NULL, NULL, &message);

printf ("%s", message);

if (result = = SQLITE_OK)

{

NSLog (@ "Delete succeeded");

}else

{

NSLog (@ "Delete failed");

}

}

Get all the model object arrays based on the model object and the name of the table at run time

-(Nsarray *) Selectalltablemodel: (ID) model

{

Nsmutablearray *dataarray = nil;

Stitching strings by model

Nsdictionary *adddic = self.dic;

NSString *name = self.tabelename;

Querying SQL statements

SELECT * from + table name

NSString *selectstr = [NSString stringwithformat:@ "SELECT * from%@", name];

sqlite3_stmt *stmt = nil;

int result = Sqlite3_prepare (db, Selectstr.utf8string,-1, &stmt, NULL);

if (result = = SQLITE_OK)

{

Defining a generic pointer below will initialize what type this generic is specifically for! Do not worry!!!!

ID Model;

Initializing an array

DataArray = [Nsmutablearray array];

while (Sqlite3_step (stmt) = = Sqlite_row)

{

The work here is the most important or save the model you are not able to get the value!!!!

This is where the runtime object is created according to runtime, so you can face all Objects!!!! Haha, huh!

model = [[[Model Class] alloc] init];

model = model;

Record the position of a data in a table each time the LOOP increases!!!!!

int i = 0;

For (NSString *key in [Adddic AllKeys])

{

if ([[Adddic Objectforkey:key] iskindofclass:[nsstring class] | | [[Adddic Objectforkey:key] Iskindofclass:[nsnumber class]] {

if ([[[Adddic Objectforkey:key] iskindofclass:[nsstring class])

{

Note here that it may be null and empty after processing to avoid KVC crash

if ((const char *) Sqlite3_column_text (stmt, i) = = NULL) {

[Model setvalue:@ "" Forkey:key];

}else

{

NSString *string = [NSString stringwithutf8string: (const char *) Sqlite3_column_text (stmt, i)];

[Model setvalue:string Forkey:key];

}

} else

{

Nsinteger index = sqlite3_column_int (stmt, i);

There's no need to worry.

NSString *string = [NSString stringwithformat:@ "%ld", (long) index];

[Model setvalue:string Forkey:key];

}

i++;

}

}

[DataArray Addobject:model];

}

}

Releasing the companion pointer

Sqlite3_finalize (stmt);

return dataarray;

}

@end

Files in DataBasehandle.h

#import <Foundation/Foundation.h>

@interface Databasehandle:nsobject

+ (Databasehandle *) Shareddatabasehandle;

-(void) opendb;

-(void) closedb;

/* Get all the properties and property contents of the object */

-(Nsdictionary *) Getallpropertiesandvaulesmodel: (ID) model;

-(void) Createtablename: (NSString *) name model: (ID) model;

-(void) Insertintotablemodel: (ID) model;

-(void) Deletefromtablemodel: (ID) model;

-(Nsarray *) Selectalltablemodel: (ID) model;

@end

According to the tool class that I wrote, you can store the data in the database according to any type of model without worrying about the database without having to write. Of course, you can store any type of model directly if you have a very good understanding of the runtime mechanism. All the properties inside the model are NSString *obj; Type of this is the data downloaded from the network, of course, the network download data may be nsnumber type but do not worry about the NSString after receiving the display after the use of formatted string can solve this problem!

Let's talk about the use of this tool class! Very simple! If not now I will add later of course also can contact me!

Runtime arbitrary type model database for easy storage

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.