iOS about Lkdbhelper Entity Object Mapping Plugin Application

Source: Internet
Author: User

A plugin Introduction:

Its GitHub address: Https://github.com/li6185377/LKDBHelper-SQLite-ORM

Full support nsarray,nsdictionary, Modelclass, NSNumber, NSString, NSDate, NSData, Uicolor, UIImage, CGRect, Cgpoint, CGSize, NSRa Nge, Int,char,float, double, long. Automation of attributes (insert and query)

Two example content:

Use Pods to load the Lkdbhelper plug-in, if you have to download the source code debugging, remember to update (the usual project remember to refer to the Libsqlite3.dylib);


This instance creates a parent entity Basebean, and subsequent entities inherit;

1: The contents of the parent entity's code

BaseBean.h content:

#import <Foundation/Foundation.h> #import <LKDBHelper/LKDBHelper.h> @interface basebean:nsobject@end// This nsobject extension class can view detailed SQL statements for the build table @interface NSObject (printsql) + (nsstring*) getcreatetablesql; @end

* Here you can put some other entities are public properties, and the Lkdbhelper database address, where Printsql is an extension to nsobject, you can view the SQL statement to create the table;

BASEBEAN.M content:

#import "BaseBean.h" @implementation basebean+ (Lkdbhelper *) getusinglkdbhelper{static lkdbhelper* db;    Static dispatch_once_t Oncetoken;        Dispatch_once (&oncetoken, ^{nsstring *sqlitepath = [Basebean Downloadpath];        nsstring* DBPath = [Sqlitepath stringbyappendingpathcomponent:[nsstring stringwithformat:@ "lkdbhelperTest.db"]];    db = [[Lkdbhelper Alloc]initwithdbpath:dbpath];    }); return DB;} /** * @author Wujunyang, 15-05-21 16:05:44 * * @brief path * @return < #return value description#> */+ (NSString *) downloadpath{nsstring *documentpath = [Nssearchpathfordirectoriesindomains (NSDocumentDirectory, NSUserDomainMask,        YES) Firstobject];        NSString *downloadpath = [documentpath stringbyappendingpathcomponent:@ "Wjy"];        NSLog (@ "%@", Downloadpath); return Downloadpath;}    @end @implementation NSObject (printsql) + (NSString *) getcreatetablesql{lkmodelinfos* infos = [self GetModelInfos]; nsstring* PrimaryKey = [Self GetprimarykEY];    nsmutablestring* table_pars = [nsmutablestring string];                for (int i=0; i<infos.count; i++) {if (i > 0) [Table_pars appendstring:@ ","];        lkdbproperty* property = [Infos objectwithindex:i];                [Self columnattributewithproperty:property];                [Table_pars appendformat:@ "%@%@", Property.sqlcolumnname,property.sqlcolumntype];                if ([Property.sqlcolumntype Isequaltostring:lksql_type_text]) {if (property.length>0) {            [Table_pars appendformat:@ "(%ld)", (long) property.length];        }} if (Property.isnotnull) {[Table_pars appendformat:@ "%@", Lksql_attribute_notnull];        } if (Property.isunique) {[Table_pars appendformat:@ "%@", Lksql_attribute_unique]; } if (Property.checkvalue) {[Table_pars appendformat:@ "%@ (%@)", lksql_attribute_check,property.ch        Eckvalue];      }  if (property.defaultvalue) {[Table_pars appendformat:@ "%@%@", Lksql_attribute_default,property.defaul        TValue]; } if (PrimaryKey && [Property.sqlcolumnname Isequaltostring:primarykey]) {[Table_pars app        endformat:@ "%@", Lksql_attribute_primarykey]; }} nsstring* createtablesql = [NSString stringwithformat:@ ' CREATE TABLE IF not EXISTS%@ (%@) ', [Self gettablename],t    Able_pars]; return createtablesql;} @end

2: The content of the child entity Carbean, which is a foreign key of the other entity Userbean

CarBean.h content: #import <Foundation/Foundation.h> #import "BaseBean.h" @interface Carbean:basebean@property ( assign,nonatomic) int carid; @property (strong,nonatomic) nsstring *carnum; @property (strong,nonatomic) NSString * Address; @property (assign,nonatomic) float carwidth; @end * Note inherit basebeancarbean.m content: #import "CarBean.h" @    Implementation carbean+ (void) initialize{//individual otherwise displayed [self removepropertywithcolumnname:@ "address"];        Multiple columns are not displayed when//[self Removepropertywithcolumnnamearray:]; Rename the new column name when the column corresponds to the table [self settablecolumnname:@ "mycarwidth" bindingpropertyname:@ "Carwidth"];} /** * @author wjy, 15-01-27 18:01:53 * * @brief whether the attributes of the parent entity class are also mapped to the SQLite library table * @return bool */+ (BOOL) iscontainparent{RE Turn YES;} /** * @author wjy, 15-01-26 14:01:01 * * @brief Set table name * @return return table name */+ (NSString *) gettablename{return @ "Carbean"; }/** * @author wjy, 15-01-26 14:01:22 * * @brief set a single primary key of the table * @return return the primary key table */+ (NSString *) getprimarykey{return @ "CA RID ";} Composite primary key This priority is highest//+ (Nsarray *) GEtprimarykeyunionarray//{//return @[@ "Carid", @ "Carnum"];//} @end 

* Main note about the ability to filter out some of the properties will not be created into the table, you can also redefine the column name, several other code is described in detail

3: Child entity Userbean, likewise inherit Basebean

UserBean.h content: #import <Foundation/Foundation.h> #import "BaseBean.h" #import "CarBean.h" @interface UserBean: Basebean@property (assign,nonatomic) int ID; @property (strong,nonatomic) nsstring *username; @property (Strong, nonatomic) NSString *password; @property (assign,nonatomic) int age; @property (strong,nonatomic) Carbean *mycar;@ ENDUSERBEAN.M content: #import "UserBean.h" @implementation userbean+ (void) initialize{    [self removepropertywithcolumnname:@ "error"];} /** *  @author wjy, 15-01-27 18:01:53 * *  @brief  Whether the attributes of the parent entity class are also mapped to the SQLite library table *  @return bool */+ (BOOL) iscontainparent{    return YES; /** *  @author wjy, 15-01-26 14:01:01 * *  @brief  Set table name *  @return Return table name */+ (NSString *) gettablename{    return @ "UserBean";} /** *  @author wjy, 15-01-26 14:01:22 * *  @brief  set a single primary key of the table *  @return return the primary key table */+ (NSString *) getprimarykey{    return @ "ID";} @end

4: Start the operation against the database

4.1 Features include the deletion of all tables, cleaning up the data of the specified table, creating a table to insert data, where inserting data will automatically determine whether the table exists, if not exist, first create the table and then insert, especially when a column is defined as an int and is a primary key, it will automatically grow if it is not assigned value

    lkdbhelper* globalhelper = [Basebean getusinglkdbhelper];        Delete all tables    [Globalhelper dropalltable];        Clean up all data    [Lkdbhelper Cleartabledata:[userbean class]];        UserBean *user=[[userbean alloc] init];    user.id=1000;  In particular, if the primary key is not assigned to it it will automatically grow    [email protected] "wujy";    [Email protected] "123456";    user.age=10;        Carbean *car=[[carbean Alloc]init];    [Email protected] "D88888";    [Email protected] "Xiamen Software Park";    car.carwidth=12.5;        User.mycar=car;        Insert data if the table does not exist it will automatically create and then insert the entity instantiation Lkdbhelper if the inheritance remembers the reference otherwise it will have no effect    [user Savetodb];        Another kind of inserting    user.age=29;    [Globalhelper Inserttodb:user];

4.2 Operations on transactions

    Things  transaction This side deliberately let it insert failed    [Globalhelper executefortransaction:^bool (Lkdbhelper *helper) {                user.id = 10 ;        [Email protected] "WUJY10";        BOOL success = [helper Inserttodb:user];                User.ID = 9;        [Email protected] "wujy09";        Success = [helper Inserttodb:user];                Repeat primary key        user.id = ten;        BOOL insertsucceed = [helper Insertwhennotexists:user];                Insert Fail        if (insertsucceed = = no)        {            ///rollback            return no;        }        else        {            ///commit            return YES;        }    ];

4.3 With regard to asynchronous operations, asynchronous operations are also supported for other operations, and callbacks are performed in a callback manner

    [Email protected] "async";    [Globalhelper inserttodb:user callback:^ (BOOL result) {        NSLog (@ "Asynchronous Insert succeeded:%@", result>[email protected] "yes": @ "no");    }];    asynchronous Query    [Globalhelper Search:[userbean class] Where:nil orderby:nil offset:0 count:100 callback:^ (NSMutableArray * Array) {        for (id obj in array) {            NSLog (@ "Async:%@", [obj Printallpropertys]);        }    ];

4.4 About the query function of several operations, pay particular attention to the wording of the conditions, other in the code has the corresponding annotations;

    nsmutablearray* Searchresultarray=nil;    Synchronous search executes the SQL statement to turn the result into an object Searchresultarray=[globalhelper searchwithsql:@ "select * from @t" Toclass:[userbean class];    for (id obj in Searchresultarray) {NSLog (@ "SQL statement:%@", [obj Printallpropertys]); }//Using the object-to-forward query operation offset is how many rows count is the query how many Searchresultarray=[userbean searchwithwhere:nil orderby:nil offset:0 Co    UNT:100];    for (id obj in Searchresultarray) {NSLog (@ "entity:%@", [obj Printallpropertys]); }//A column is queried when the operation count is 0 when all columns are checked nsarray* namearray = [UserBean searchcolumn:@ "userName" Where:nil orderby:nil offset:    0 count:0];        NSLog (@ "%@", [NameArray componentsjoinedbystring:@ ","]);    Operations when querying multiple columns nsarray* twocolumn=[userbean searchcolumn:@ "Id,username" Where:nil orderby:nil offset:0 count:0];    For (UserBean *obj in Twocolumn) {NSLog (@ "%d-%@", obj.id,obj.username); }//combination query four kinds and or like in Searchresultarray=[userbean searchwithwhere:[nsstring stringwithformat:@ "UserName like '%%jy%% ' "] orderby:nil offset:0 count:0];        NSLog (@ "like:%lu", Searchresultarray.count); Searchresultarray=[userbean searchwithwhere:[nsstring stringwithformat:@ "age=29 and UserName= ' WUJY '"] OrderBy:nil    offset:0 count:0];        NSLog (@ "and:%lu", Searchresultarray.count); Searchresultarray=[globalhelper Search:[userbean class] where:@{@ "age": @29,@ "UserName": @ "wujy"} orderby:nil Offset    : 0 count:0];        NSLog (@ "and%lu", searchresultarray.count); Searchresultarray=[userbean searchwithwhere:[nsstring stringwithformat:@ "age=29 or userName= ' WUJY '"] OrderBy:nil    offset:0 count:0];        NSLog (@ "OR%lu", searchresultarray.count); Searchresultarray=[userbean searchwithwhere:[nsstring stringwithformat:@ "age in (10,29)"] OrderBy:nil offset:0 Count    : 0];        NSLog (@ "in%lu", Searchresultarray.count);    Searchresultarray=[globalhelper Search:[userbean class] where:@{@ "age": @[@10,@29]} orderby:nil offset:0 count:0];        NSLog (@ "in%lu", Searchresultarray.count); Query the number of eligible bars   Nsinteger rowcount=[userbean rowcountwithwhere:@ "age=29"]; NSLog (@ "RowCount%ld", rowCount);
* Note: Single condition:  @ "ROWID = 1"  or  @{@ "rowID": @1} Multiple conditions: @ "ROWID = 1 and sex = 0"  or    @{@ "rowid": @1,@ "Sex": @0} If the condition is an or type, it can only be in the form of a string: @ "ROWID = 1 or sex = 0" in Condition: @ "rowID in"   or     @{@ "rowID": @[@1,@2,@3]} Multiple conditions with in:@ "rowID In (@{@) and sex=0 "   or"    rowid ": @[@1,@2,@3],@" Sex ": @0} time can also be used only with strings: @" date >= ' 2013-04-01 00:00:00 ' " Like also can only use string: @ "UserName like '%%jy%% '"

4.5 Update actions

//with conditional update [email protected] "riding wave handsome";    BOOL isupdate=[globalhelper updatetodb:user where:@{@ "ID": @10}];        NSLog (@ "Update succeeded:%@", isupdate>[email protected] "yes": @ "no"); Update Searchresultarray=[userbean searchwithwhere:[nsstring stringwithformat:@ "username= '%@ '", @ "WUJY", as per condition    Orderby:nil offset:0 count:100];    User=[searchresultarray Firstobject];    [email protected] "aa123456";    BOOL moreupdate=[globalhelper Updatetodb:user Where:nil];        NSLog (@ "Updated upon condition:%@", moreupdate>[email protected] "yes": @ "no"); Update Access table name update content with condition update BOOL updatetab=[globalhelper updatetodbwithtablename:@ "UserBean" set:@ "password= ' aa123456 '"    where:@ "age=10"];        NSLog (@ "Access table name update content updated with conditions:%@", updatetab>[email protected] "yes": @ "no"); Update by real class BOOL Updateclass=[globalhelper Updatetodb:[userbean class] set:@ "password= ' cnblogs '" where:@ "Username= '    Wujy ' "]; NSLog (@ "Update according to the real class:%@", updateclass>[email protected] "yes": @ "no"); 

4.6 Delete Operations

    Delete function    User=[globalhelper Searchsingle:[userbean class] where:@{@ "Age": @10} Orderby:nil];    BOOL Ishas=[globalhelper Isexistsmodel:user];    if (Ishas) {        [globalhelper deletetodb:user];    }        Delete multiple    BOOL isdeletemore=[globalhelper Deletewithclass:[userbean class] where:@ "age=29"];    if (isdeletemore) {        NSLog (@ "All eligible are deleted");    }

iOS about Lkdbhelper Entity Object Mapping Plugin Application

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.