【问题标题】:CoreData objects or SQL statements for complex reporting?用于复杂报告的 CoreData 对象或 SQL 语句?
【发布时间】:2012-09-27 10:42:39
【问题描述】:

我的 iOS 应用有一个从 PostgreSQL 数据库继承的模型。该应用程序具有报告功能,未来可能会变得更加复杂。此外,可能需要将本地应用数据与 PostgreSQL 数据库服务器同步。

到目前为止,我已经使用 CoreData 对象来读取、写入和删除数据。我一直在翻译 SQL 查询以使用 CoreData 语言,但发现它对其中一些来说不必要地麻烦,例如:

select sum(amount), date from db.table group by date;

这只是一个示例,该应用程序将来可能需要更复杂的报告查询。因此,我正在考虑从 CoreData 切换到直接查询 SQLite(我可以使用已经编写的查询来查询 PostgreSQL DB)。

我的问题是:

  • 考虑到报告是应用程序的核心功能(即需要重要的 SELECT 查询),是否值得继续使用 CoreData 而不是 SQL 查询?
  • 在同一个存储中同时使用 SQL(用于复杂的 SELECT 查询)和 CoreData(用于应用程序的其余部分)是否可行?

【问题讨论】:

    标签: iphone objective-c ios sqlite core-data


    【解决方案1】:

    一旦你掌握了语法,我会转向 CoreData,它非常快速且非常简单。最大的不同是你用这样的东西替换 sql 语句:

     // Retrieve the entity from the local store -- much like a table in a database
        NSEntityDescription *entity = [NSEntityDescription entityForName:@"AppSettings" inManagedObjectContext:managedObjectContext];
        NSFetchRequest *request = [[NSFetchRequest alloc] init];
        [request setEntity:entity];
    
    
    // Set the predicate -- much like a WHERE statement in a SQL database
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"version == %@", @"Default"];
    [request setPredicate:predicate];
    
    
    // Set the sorting -- mandatory, even if you're fetching a single record/object
    
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"version" ascending:YES];
    NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
    [request setSortDescriptors:sortDescriptors];
    sortDescriptors = nil;
    sortDescriptor = nil;
    
    // Request the data -- NOTE, this assumes only one match, that 
    // yourIdentifyingQualifier is unique. It just grabs the first object in the array. 
    AppSettings *appSettings1 =[[managedObjectContext executeFetchRequest:request error:&error] objectAtIndex:0];
    
    request = nil;
    
    
    //Update the object
    appSettings1.backGroundImage = [NSNumber numberWithInt: backGroundGraphics.selectedSegmentIndex];
    

    希望这有助于 MAC 应用商店中开发者部分下的工具,真正帮助 Core Data Editor 一直是一种用途。

    您始终可以直接使用 SQL,但数据存储结构与 Core Data 字段看起来有点滑稽。

    【讨论】:

    • 核心数据编辑器,我必须检查一下!
    • 我已经熟悉你提到的那些东西了。 CoreData 在那些简单的情况下运行良好,我的特殊问题是在 CoreData 和复杂的 SELECT 查询中相当于 GROUP BY。感谢您将我指向核心数据编辑器。
    【解决方案2】:

    出于同样的原因,我删除了核心数据,我有一些非常复杂的查询,翻译为核心数据使用实在是太痛苦了。在我看来,只需坚持使用纯 SQLLite 并手动编写 SQL 即可。或者,您可以使用 FMDB 作为 SQLlite https://github.com/ccgus/fmdb 的包装器

    【讨论】:

    • 我一定会检查 FMDB。您是否尝试过同时使用 SQL 和 CoreData 方法来查询同一个模型?
    • 不,我还没有尝试同时使用它们,那将更加痛苦 IMO。此外,第一次“select sum(amount), date from db.table group by date”不是那么好和容易写出来吗:)
    猜你喜欢
    • 2017-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多