一次抓取,就可以多次查询请求。
// fetch all -> filter by predicate
@interface RequestInMemory : NSObject
@property(nonatomic, strong) NSArray *fetchedContents;
// initialize class + fetch data from CoreData
+ (instancetype)memoryEntityDescription:(NSEntityDescription *) entityDescription context:(NSManagedObjectContext *) managedObjectContext;
+ (instancetype)memoryEntityDescription:(NSEntityDescription *) entityDescription predicate:(NSPredicate *) predicate context:(NSManagedObjectContext *) managedObjectContext;
#pragma mark - manually
// manually update internal database
// when initialize the class, automatically call this method.
- (NSArray *)fetchAll;
- (NSArray *)fetchWithPredicate:(NSPredicate *) predicate;
#pragma mark - filter helper
- (BOOL)testWithPredicate:(NSPredicate *) predicate;
- (NSArray *)findFirstWithPredicate:(NSPredicate *) predicate;
- (NSArray *)findAllWithPredicate:(NSPredicate *) predicate;
@end
第一次,RequestInMemory
只抓取所有数据一次。
您可以在下次不需要访问CoreData的情况下进行查询请求。
您尝试使用pod try RequestInMemory
- (void)viewDidAppear:(BOOL) animated {
[super viewDidAppear:animated];
CFTimeInterval startTime = CACurrentMediaTime();
{
for (size_t i = 0; i < 1000; i++) {
@autoreleasepool {
[self performCoreData];
}
}
}
CFTimeInterval endTime = CACurrentMediaTime();
NSLog(@"Total Runtime performCoreData: %g s", endTime - startTime);
CFTimeInterval startTime_b = CACurrentMediaTime();
{
self.personInMemory = [RequestInMemory memoryEntityDescription:[Person MR_entityDescription] context:[NSManagedObjectContext MR_defaultContext]];
for (size_t i = 0; i < 1000; i++) {
@autoreleasepool {
[self performRequestInMemory];
}
}
}
CFTimeInterval endTime_b = CACurrentMediaTime();
NSLog(@"Total Runtime performRequestInMemory: %g s", endTime_b - startTime_b);
}
- (void)performRequestInMemory {
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"%K == %d", @"age", 10];
[self.personInMemory findFirstPredicate:predicate];
}
- (void)performCoreData {
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"%K == %d", @"age", 10];
[Person MR_findFirstWithPredicate:predicate];
}
结果
Total Runtime performCoreData: 1.53506 s
Total Runtime performRequestInMemory: 0.956278 s
RequestInMemory
抓取所有数据。换句话说,RequestInMemory
是内存占用大户。
不够有效,但简单。(欢迎Pull Requests!更多有效的方法!)
git checkout -b my-new-feature
git commit -am '添加一些功能'
git push origin my-new-feature
MIT