BZObjectStore 会自动将您的模型存储到 SQLite 表中,并为您的应用程序提供有用选项。
BZObjectStore 可以使用 CocoaPods 进行安装。
pod 'BZObjectStore'
pod 'BZObjectStore/CoreLocation' // if needed
pod 'BZObjectStore/ActiveRecord' // if needed
pod 'BZObjectStore/Parse' // if needed
#import "BZObjectStore.h"
NSError *error = nil;
// open datbase
BZObjectStore *os = [BZObjectStore openWithPath:@"database.sqlite" error:&error];
// save a object
[os saveObject:YOUROBJECT error:&error];
// close database
[os close];
处理后,您可以在控制台中找到 'database path=/XXXX/database.sqlite'。
使用您的 SQLite 工具打开此文件并检查表。
#import "BZObjectStore.h"
@interface SampleModel : NSObject
@property (nonatomic,strong) NSString *name;
@property (nonatomic,assign) NSInteger price;
@property (nonatomic,strong) SampleModel *sample;
@end
@implementation SampleModel
@end
SampleModel *sample1 = [[SampleModel alloc]init];
sample1.name = @"sample1";
sample1.price = 100;
SampleModel *sample2 = [[SampleModel alloc]init];
sample2.name = @"sample2";
sample2.price = 50;
sample2.sample = sample1;
#import "BZObjectStore.h"
NSError *error = nil;
// default path is NSLibraryDirectory
BZObjectStore *os = [BZObjectStore openWithPath:@"database.sqlite" error:&error];
// open in memory
BZObjectStore *os = [BZObjectStore openWithPath:nil error:&error];
// save a object
[os saveObject:sample1 error:&error];
// save objects in array
[os saveObjects:@[sample1,sample2] error:&error];
// fetch objects
NSArray *fetchObjects = [os fetchObjects:[SampleModel class] condition:nil error:&error];
// fetch latest data from database
SampleModel *latest = [os refreshObject:sample1 error:&error];
// fetch referencing objects
NSArray *referencingObjects = [os fetchReferencingObjectsTo:sample1 error:&error];
// delete a object
[os deleteObject:sample1 error:&error];
// delete objects
[os deleteObjects:[SampleModel class] condition:nil error:&error];
// delete objects in array
[os deleteObject:@[sample1,sample2] error:&error];
BZObjectStoreConditionModel *fetchCondition = [BZObjectStoreConditionModel condition];
fetchCondition.sqlite.where = @"name = 'sample1' and price > 50";
fetchCondition.sqlite.orderBy = @"name desc";
NSArray *objects = [os fetchObjects:[SampleModel class] condition:fetchCondition error:&error];
BZObjectStoreConditionModel *deleteCondition = [BZObjectStoreConditionModel condition];
deleteCondition.sqlite.where = @"name = 'sample1'";
[os deleteObjects:[SampleModel class] condition:deleteCondition error:&error];
// close database
[os close];
NSNumber *count = [os count:[SampleModel class] condition:nil error:&error];
NSNumber *max = [os max:@"price" class:[SampleModel class] condition:nil error:&error];
NSNumber *min = [os min:@"price" class:[SampleModel class] condition:nil error:&error];
NSNumber *sum = [os sum:@"price" class:[SampleModel class] condition:nil error:&error];
NSNumber *total = [os total:@"price" class:[SampleModel class] condition:nil error:&error];
NSNumber *avg = [os avg:@"price" class:[SampleModel class] condition:nil error:&error];
[os inTransaction:^(BZObjectStore *os, BOOL *rollback) {
NSError *error = nil;
[os saveObject:sample1 error:&error];
[os saveObject:sample2 error:&error];
// rollback if needed
*rollback = YES;
}];
// Improve response time (Not required but recommended)
[os registerClass:[SampleModel class] error:&error];
[os unRegisterClass:[SampleModel class] error:&error];
有三个类
BZObjectStoreConditionModel
- 此类包含以下类。您在需要时创建一个实例并将其设置到每个方法中。BZObjectStoreSQLiteConditionModel
- SQLite条件。BZObjectStoreReferenceConditionModel
- 引用对象条件。// create insntance
BZObjectStoreConditionModel *condition = [BZObjectStoreConditionModel condition];
// access to BZObjectStoreSQLiteConditionModel
condition.sqlite.XXXXX
// access to BZObjectStoreReferenceConditionModel
condition.reference.XXXXX
// where condition
condition.sqlite.where = @"name = ?";
// where parameters
condition.sqlite.parameters = @[@"sample1"];
// order By
condition.sqlite.orderBy = @"code desc";
// limit
condition.sqlite.limit = @20;
// offset
condition.sqlite.offset = @20;
// set object referencing from
condition.reference.from = sample1;
// no object referencing from
condition.reference.from = [NSNull null];
// set object referenced to
condition.reference.to = sample1;
// no object referenced to
condition.reference.from = [NSNull null];
定义相同属性
#import "BZObjectStoreModelInterface.h"
@interface OrderModel : NSObject
@property (nonatomic,strong) NSString<OSIdenticalAttribute> *no;
@property (nonatomic,assign) NSArray *items;
@end
忽略属性
#import "BZObjectStoreModelInterface.h"
@interface OrderModel : NSObject
@property (nonatomic,strong) NSString<OSIdenticalAttribute> *no;
@property (nonatomic,assign) NSArray *items;
@property (nonatomic,assign) NSIndexPath<OSIgnoreAttribute> *indexPath;
@end
在删除对象时不删除关联对象。
#import "BZObjectStoreModelInterface.h"
@interface OrderModel : NSObject
@property (nonatomic,strong) NSString<OSIdenticalAttribute> *no;
@property (nonatomic,strong) NSArray<OSWeakReferenceAttribute> *items;
@end
@interface ItemModel : NSObject
@property (nonatomic,strong) NSString<OSIdenticalAttribute> *code;
@property (nonatomic,assign) NSInteger price;
@end
仅在refreshObject方法中获取关联对象,在fetchObjects方法中不获取。
#import "BZObjectStoreModelInterface.h"
@interface NodeModel : NSObject
@property (nonatomic,strong) NSArray<OSFetchOnRefreshingAttribute> *children;
@end
值是空时不要更新属性。
#import "BZObjectStoreModelInterface.h"
@interface ProfileModel : NSObject
@property (nonatomic,strong) NSString *name;
@property (nonatomic,strong) UIImage<OSNotUpdateIfValueIsNullAttribute> *image;
@end
只更新一次属性。
#import "BZObjectStoreModelInterface.h"
@interface ProfileModel : NSObject
@property (nonatomic,strong) NSString *name;
@property (nonatomic,strong) NSDate<OSOnceUpdateAttribute> *registAt;
@property (nonatomic,strong) NSDate *updateAt;
@end
忽略父类属性
#import "BZObjectStoreModelInterface.h"
@interface OrderModel : NSObject
@property (nonatomic,strong) NSString *remarks;
@end
@interface DailyOrderModel : OrderModel<OSIgnoreSuperClass>
@property (nonatomic,strong) NSString *no;
@property (nonatomic,assign) NSArray *details;
@end
使用sqlite的FTS3
#import "BZObjectStoreModelInterface.h"
@interface Address : NSObject<OSFullTextSearch3>
@property (nonatomic,assign) NSString *address;
@end
使用sqlite的FTS4
#import "BZObjectStoreModelInterface.h"
@interface Address : NSObject<OSFullTextSearch4>
@property (nonatomic,assign) NSString *address;
@end
优先插入性能
#import "BZObjectStoreModelInterface.h"
@interface LogModel : NSObject<OSInsertPerformance>
@property (nonatomic,assign) NSString *code;
@property (nonatomic,assign) NSString *description;
@end
优先更新性能
#import "BZObjectStoreModelInterface.h"
@interface ProfileModel : NSObject<OSUpdatePerformance>
@property (nonatomic,assign) NSString *name;
@end
如果是原始类型,请改在您的模型中覆盖attributeIsXXXX方法而不是这些选项。
这些方法定义在OSModelInterface协议中。
该接口提供了额外功能。
导入BZObjectStoreModelInterface.h文件,在您的模型中实现OSModelInterface协议,并覆盖您需要的方法。
并覆盖您需要的方法。
+ (NSString*)OSTableName
{
return @"table_name_you_want";
}
+ (NSString*)OSColumnName:(NSString*)attributeName
{
if ([attributeName isEqualToString:@"column_name_you_want_to_change"]) {
return @"column_name_you_want";
}
return attributeName;
}
- (void)OSModelDidLoad
{
// your operation
}
- (void)OSModelDidSave
{
// your operation
}
- (void)OSModelDidDelete
{
// your operation
}
+ (BOOL)attributeIsOSIdenticalAttribute:(NSString*)attributeName
{
if ([attributeName isEqualToString:@"foo"]) {
return YES;
}
return NO;
}
+ (BOOL)attributeIsOSIgnoreAttribute:(NSString*)attributeName
{
if ([attributeName isEqualToString:@"foo"]) {
return YES;
}
return NO;
}
+ (BOOL)attributeIsOSWeakReferenceAttribute:(NSString*)attributeName
{
if ([attributeName isEqualToString:@"foo"]) {
return YES;
}
return NO;
}
+ (BOOL)attributeIsOSNotUpdateIfValueIsNullAttribute:(NSString*)attributeName
{
if ([attributeName isEqualToString:@"foo"]) {
return YES;
}
return NO;
}
+ (BOOL)attributeIsOSSerializableAttribute:(NSString*)attributeName
{
if ([attributeName isEqualToString:@"foo"]) {
return YES;
}
return NO;
}
+ (BOOL)attributeIsOSOnceUpdateAttribute:(NSString*)attributeName
{
if ([attributeName isEqualToString:@"foo"]) {
return YES;
}
return NO;
}
可以使用后台进程方法。
导入 BZObjectStoreBackground.h 并调用每个方法名 + 'InBackground' 方法。
#import "BZObjectStore.h"
[os saveObjectInBackground:savedObject completionBlock:^(NSError *error) {
if (!error) {
// succeed
} else {
// failed
}
}];
// refer BZObjectStoreBackground.h about other methods
Objective-C 和 C 数据类型 | SQLite 数据类型 | 映射列名 | 备注 |
---|---|---|---|
char* | INTEGER | attributeName | |
short | INTEGER | attributeName | |
int | INTEGER | attributeName | |
long | INTEGER | attributeName | |
long long | INTEGER | attributeName | |
double | REAL | attributeName | |
float | REAL | attributeName | |
unsigned char* | INTEGER | attributeName | |
unsigned short | INTEGER | attributeName | |
unsigned int | INTEGER | attributeName | |
unsigned long | INTEGER | attributeName | |
NSInteger | INTEGER | attributeName | |
CGFloat | REAL | attributeName | |
CGPoint | REAL | attributeName + '_x',+ '_y' | 分为两列 |
CGSize | REAL | attributeName + '_width',+ '_height' | 分为两列 |
CGRect | REAL | attributeName + '_x', + '_y', + '_width', + '_height' | 分为四列 |
NSRange | INTEGER | attributeName + '_length', + '_location' | 分为两列 |
NSDate | REAL | attributeName | 保存为 Unix 时间 |
NSData | BLOB | attributeName | |
NSString | TEXT | attributeName | |
NSMutableString | TEXT | attributeName | |
NSNull | BLOB | attributeName | 保存为 null |
NSNumber | INTEGER | attributeName | 保存为原始值 |
NSURL | TEXT | attributeName | 保存为绝对 URL 字符串 |
NSValue | BLOB | attributeName | 保存为序列化数据 |
UIColor | TEXT | attributeName | 保存为 RGBA 字符串 |
UIImage | BLOB | attributeName | 保存为 GIF 二进制数据 |
NSArray | INTEGER | attributeName | |
NSDictionary | INTEGER | attributeName | |
NSSet | INTEGER | attributeName | |
NSOrderedSet | INTEGER | attributeName | |
NSMutableArray | INTEGER | attributeName | |
NSMutableDictionary | INTEGER | attributeName | |
NSMutableSet | INTEGER | attributeName | |
NSMutableOrderedSet | INTEGER | attributeName | |
NSObject | INTEGER | attributeName | |
ID | NONE | attributeName,attributeName + '_attributeType' | 分为两列 |
CLLocationCoordinate2D | REAL | attributeName + '_latitude',+ '_longitude' | 分为两列 |
CLLocation | REAL | attributeName + '_altitude',+ '_latitude',+ '_longitude',+ '_course',+ '_horizontalAccuracy',+ '_speed',+ '_timestamp',+ '_verticalAccuracy' | 分为八列 |
其他 C 结构将保存为 NSValue。
NSObject、NSArray、NSDictionary、NSSet、NSOrderedSet 中的对象将自动映射到 SQLite 表中。
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
BZObjectStore *os = [BZObjectStore openWithPath:@"database.sqlite" error:&error];
[BZActiveRecord setupWithObjectStore:os];
}
#import "NSObject-ActiveRecord.h"
@interface SampleModel : NSObject
@property (nonatomic,strong) NSString *name;
@property (nonatomic,assign) NSInteger price;
@property (nonatomic,strong) SampleModel *sample;
@end
@implementation SampleModel
@end
- (void)foo
{
NSError *error = nil;
SampleModel *sample = [SampleModel alloc]init];
[sample save:&error];
NSArray *samples = [SampleModel fetchs:nil error:&error];
[sample delete:&error];
}
- (void)foo
{
NSError *error = nil;
SampleModel *sample = [SampleModel alloc]init];
[sample OSSave:&error];
NSArray *samples = [SampleModel OSFetchs:nil error:&error];
[sample OSDelete:&error];
}
BZObjectStore支持以下Parse对象。
Parse数据类型 | SQLite 数据类型 | 映射列名 | 备注 |
---|---|---|---|
PFGeoPoint | REAL | attributeName + '_latitude',+ '_longitude' | 分为两列 |
PFFile | TEXT,BLOB | attributeName + '_name',+ '_data' | 分为两列 |
// migrate database
[os migrate error:&error];
当仅向模型添加属性时,迁移将自动运行。所以不要运行'migrate'方法。
#import "BZObjectStore.h"
#import "FMDatabaseQueue.h"
#import "FMDatabase.h"
- (void)foo
{
BZObjectStore *os = [BZObjectStore openWithPath:@"database.sqlite" error:nil];
FMDatabaseQueue *dbQueue = os.dbQueue;
[dbQueue inDatabase:^(FMDatabase *db) {
FMResultSet *rs = [db getTableSchema:@"SampleModel"];
while (rs.next) {
NSString *columnName = [rs stringForColumnIndex:1];
}
[rs close];
}];
[os close];
}
#import "FMDatabase.h"
- (void)transactionDidBegin:(FMDatabase *)db
{
// called when call fetch,delete,save methods
}
- (void)transactionDidEnd:(FMDatabase *)db
{
// called when call fetch,delete,save methods
}
作者:Shimada Takeshi
历史:[https://github.com/expensivegasprices/BZObjectStore/History.md](https://github.com/expensivegasprices/BZObjectStore/History.md)
灵感来自AFNetworking,JSONModel和FMDB。