Combined with objC Runtime, further encapsulation of FMDB makes CRUD operations on a single model easier and faster. Such as:

@interface Rectangle : NSObject

@property (nonatomic, assign) NSInteger width;
@property (nonatomic, assign) NSInteger length;
@property (nonatomic, copy) NSString *name;

@end

@implementation Rectangle

@endCopy the code

Get the SXJDatabaseManager object:

SXJDatabaseManager *manager = [SXJDatabaseManager sharedManager];Copy the code

Create the table with a Rectange:

[manager createTable:[Rectangle class]];Copy the code

Create the table with Rectange and specify the primary key:

[manager createTableWithClass:[Rectangle class] primaryKeyNameArray:@[@"name"]];Copy the code

Insert data into table;

Rectangle *rect = [Rectangle new];
rect.name = @"rectangle1";
rect.width = 10;
rect.length = 25;
[manager insertModel:rect];Copy the code

Delete data:

NSDictionary *cond = @{@"name": @"rectangle1"};
[manager deleteRecordFromTable:[Rectangle class] condition:cond];Copy the code

For more usage, refer to the API in SXJDatabasemanager.h.

Implementation approach

There’s nothing particularly hard about getting an attribute of an object, and then getting the type encoding for each attribute, and concatenating strings.

At implementation time, after reading the data from the database, the Runtime knows the type of each attribute, but how to dynamically define a variable of the corresponding type at runtime is confusing. As it turns out, FMResultSet has a resultDictionary attribute, so I’m going to KVC directly.

seeresultDictionaryImplementation of, directly define aidType, if it’s an object, put it in the dictionary, if it’s a native data type, use itNSNumberWrap it up and put it in a dictionary.

Existing problems

Since only single table operations are considered and certain types of attributes are not serialized for storage, collection types such as NSDictionary, NSArray, and NSSet are not supported. In the future, multi-table schemes are preferred if they are to be supported.

If you think this implementation is ok or helps you, welcome Star