CoreData的易用替代品
CoreData是一个非常酷的框架。我已经用它完成了许多用途,它通常很好地满足了我的需求。然而,一段时间之前,我正在开发一个需要对象同时修改后台处理线程和UI线程的具有大量线程的应用程序。为了在不抛出异常的情况下在CoreData中完成这项任务,我需要进行大量的锁定,导致我的应用程序变得极其缓慢。因此,FringeData诞生了。它从一开始就旨在在内存使用、速度和线程安全之间取得平衡。您可以从多个线程安全地读取和写入FringeDataObject,而不用担心锁定(它为您处理)。此外,由于它使用JSON格式的文件作为后端存储,因此很容易向FringeDataObject的派生对象中添加或删除属性。
这实现了支持索引两个属性的一个简单的FringeObject类型。
@interface MyObject : FringeObject
@property (nonatomic, strong) NSString* stringProperty;
@property (nonatomic, strong) NSDictionary *dictProperty;
@property (nonatomic, assign) float floatProperty;
@end
static NSString *const kMyBasePath = @"/tmp/MyObject";
@implementation MyObject
@dynamic stringProperty;
@dynamic floatProperty;
+ (NSURL*)defaultCommitPath {
return [NSURL fileURLWithPath:[kMyBasePath stringByAppendingPathComponent:@"Data"];
}
+ (NSSet*)indexedPropertyNames {
return [NSSet setWithArray:@[ @"stringProperty", @"floatProperty" ];
}
+ (NSURL*)indexURLForProperty:(NSString*)name withValue:(id)value forObject:(FringeObject*)object {
NSString *pathFragment = nil;
if( [name isEqualToString:@"stringProperty"] ) {
NSString *first = [value substringToIndex:1];
if( [first rangeOfCharacterFromSet:[NSCharacterSet letterCharacterSet]].location != NSNotFound )
pathFragment = [@"FirstLetter" stringByAppendingPathComponent:[first uppercaseString]]];
}
else if( [name isEqualToString:@"floatProperty"] ) {
float floatValue = [value floatValue];
if( floatValue < 0.f )
pathFragment = @"PosNeg/-1";
else if( floatValue > 0.f )
pathFragment = @"PosNeg/+1";
else
pathFragment = @"PosNeg/0";
}
if( pathFragment )
return [NSURL fileURLWithPath:[kMyBasePath stringByAppendingPathComponent:pathFragment]];
return nil;
}
@end
要创建对象的几个实例,您可能
MyObject *obj;
obj = [MyObject new];
obj.stringProperty = @"An object";
obj.floatProperty = -543.f;
[FringeDataUtils save:obj];
obj = [MyObject new];
obj.stringProperty = @"Another object";
obj.floatProperty = 432.f;
[FringeDataUtils save:obj];
obj = [MyObject new];
obj.stringProperty = @"Yet another object";
obj.floatProperty = -354.f;
[FringeDataUtils save:obj];
为了找到所有以字符串属性以'a'开头且浮点属性为负数的实例
NSArray *paths = @[ [MyObject indexURLForProperty:@"stringProperty" withValue:@"a" forObject:nil],
[MyObject indexURLForProperty:@"floatProperty" withValue:@-1.f forObject:nil]
];
NSArray *objects = [FringeDataUtils rootObjectsAtAllPaths:paths limit:0];
NSLog(@"result: %@", objects); // should print "result: <MyObject [UUID] {stringProperty: \"An object\", floatProperty: -543.0, dictProperty: nil}>"