Jrdb:ios to Fmdb's super-usable package

Source: Internet
Author: User

In their own development, each use of the database will be entangled in the use of CoreData or Fmdb. CoreData Although the API is simple, but the call stack is very complex, to initialize a context requires at least 20 lines of code ...

Obviously, for such a disgusting situation, our big GitHub must be someone who will jump out of the way to solve this problem. So there came the magicrecord of the CoreData. When I first met this library, it was pretty easy to make me want to replace all the project databases with CoreData. Two sentences to resolve the initialization of the CoreData call stack, a sentence to complete the database version upgrade and automatic Data merge update (although we rarely use).

While this does not solve a fundamental problem, each object in CoreData is bound to a context, causing many of our business requirements to be created with our own private context and then saved to the main context when it needs to be updated. This has led us to maintain one more private context property in the controller or in our own business class.

As a result, the Fmdb is finally selected for encapsulation.

Prior to the Java background, the Fmdb for Hibernate-style encapsulation, using runtime parsing, without inheriting any base class (in Swift to inherit NSObject), as long as the implementation of a persistent protocol and implement the method, masking the basic database and table operations.

Project Introduction:

Jrdb: An iOS library for Fmdb-class hibernate encapsulation that supports objective-c and Swift.

Description

    • Use the pattern of classification, imitate hibernate, simple encapsulation of Fmdb

    • Support pod Installation "pod ' Jrdb '", podfile need to add use_framework!

    • Use the protocol, do not inherit the base class, to any nsobject can carry on the storage operation

    • Support for Swift and OBJECTIVE-C

    • Supported data types: Basic data types (int,double, etc.), string,nsdata,nsnumber,nsdate

Note: The basic data type of SWIFT does not support the option type, neither does it support int? Int! And so on, the object type supports the option type

Installation (Installation)

123 use_frameworks!pod ‘JRDB‘@import JRDB;

Usage

Save (saved)

    • Objective-c

1234567891011121314 person *p =  [[person alloc] init]; p.a_int = 1; P.B_UNSIGNED_INT = 2; p.c_long = 3; p.d_long_long = 4; p.e_unsigned_long = 5; p.f_unsigned_long_long = 6; p.g_float = 7.0; p.h_double = 8.0; p.i_string = @ "9" P.J_NUMBER = @10; p.k_data = [nsdata data]; p.l_date = [nsdate date]; [p jr_save];
    • Swift

Classes requiring storage in Swift need to inherit NSObject (use to runtime)

The Object that you want to persistent should inherit from NSObject

12345 let p = Person()p.name = "name"p.age = 10p.birthday = NSDate()p.jr_save()

Update (Updated)

123 Person *p = [Person jr_findAll].firstObject;p.name = @"abc";[p jr_update columns:nil];

Column: Field name that needs to be updated, incoming null for full-scale update

Delete (remove)

12 Person *p = [Person jr_findAll].firstObject;[p jr_delete];

Select( Find)

    • General find

123 Person *p = [Person jr_findByPrimaryKey:@"111"];NSArray *list = [Person jr_findAll];NSArray *list1 = [Person jr_findAllOrderBy:@"_age"isDesc:YES];
    • Conditional query

12345678 NSArray *condis = @[     [JRQueryCondition condition:@"_l_date < ?" args:@[[NSDate date]] type:JRQueryConditionTypeAnd],     [JRQueryCondition condition:@"_a_int > ?"args:@[@9] type:JRQueryConditionTypeAnd],];NSArray *arr = [Person jr_findByConditions:condis                      groupBy:@"_room"                      orderBy:@"_age"                      limit:@" limit 0,13 "                      isDesc:YES];
    • Sql

12 NSString *sql = @"select * from Person where age = ?";NSArray *list = [Person jr_executeSql:sql args:@[@10]];

Other (others)

Protocol: Jrpersistent

123456789101112131415161718192021 @protocol JRPersistent @required- (void)setID:(NSString * _Nullable)ID;- (NSString * _Nullable)ID;@optional/** *  返回不用入库的对象字段数组 *  The full property names that you want to ignore for persistent *  @return array */+ (NSArray * _Nullable)jr_excludePropertyNames;/** *  返回自定义主键字段 *  @return 字段全名 */+ (NSString * _Nullable)jr_customPrimarykey;/** *  返回自定义主键值 *  @return 主键值 */- (id _Nullable)jr_customPrimarykeyValue;@end

Primary key

The default primary key for each object is the ID, the UUID string.

You can implement the Jr_customprimarykey and Jr_customprimarykeyvalue methods to customize the primary key.

Default NSObject Classification Implementation

12345678910111213141516171819202122 @interface NSObject (JRDB) (...methods)@endJRDBMgr@interface JRDBMgr : NSObject@property (nonatomic, strong) FMDatabase *defaultDB;+ (instancetype)shareInstance;+ (FMDatabase *)defaultDB;- (FMDatabase *)createDBWithPath:(NSString *)path;- (void)deleteDBWithPath:(NSString *)path;/** *  在这里注册的类,使用本框架的数据库将全部建有这些表 *  @param clazz 类名 */- (void)registerClazzForUpdateTable:(Class)clazz;- (NSArray *)registedClazz;/** * 更新默认数据库的表(或者新建没有的表) * 更新的表需要在本类先注册 */- (void)updateDefaultDB;- (void)updateDB:(FMDatabase *)db;@end

Jrdbmgr holds a default database (~/documents/jrdb/jrdb.sqlite), and any operation that does not specify a database operates on this database. The default database can be set by itself.

Method

1 - (void)registerClazzForUpdateTable:(Class)clazz;

Classes registered in Jrdbmgr, you can use the

1 -(void)updateDB:(FMDatabase *)db

Make a unified update or create a table.

Table operation (Tables operation)

Create (Build table)

1234567891011 // FMDatabase+JRDB 方法[[JRDBMgr defaultDB] createTable4Clazz:[Person class]];[Person jr_createTable];// 删除原有的表,重新创建[[JRDBMgr defaultDB] truncateTable4Clazz:[Person class]];[Person jr_truncateTable];//保存时,若发现没有表,将自动创建[person jr_save];Update 【更新表】[[JRDBMgr defaultDB] updateTable4Clazz:[Person class]];[Person jr_updateTable];

When you update a table, only non-existent fields are added, field properties are not modified, fields are not deleted, and you need to write your own SQL statements to modify them if necessary

Drop (delete table)

12 [[JRDBMgr defaultDB] dropTable4Clazz:[Person class]];[Person jr_dropTable];

Thread operation (threading operation)

Multithreaded operation using Fmdb's own fmdatabasequeue

123 [person jr_saveWithComplete:^(BOOL success) {    NSLog(@"%d", success);}];

Any operation with complete block will be put into fmdatabasequeue for sequential execution.

Note: All database operations that require immediate return results, or that affect other operations, are recommended to be placed on the main thread for updates, bulk updates, and multi-threaded operations of the database, using the complete block operation.

Moreusage

Jrdb:ios to Fmdb's super-usable package

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.