简体   繁体   English

检查数据库中现有数据的最佳方法(iOS)

[英]Best way to check existent data in the database (iOS)

I'm developing an app that manages messages, and I want the app connects to the server, get messages and save them in the database(coredata). 我正在开发一个用于管理消息的应用程序,并且希望该应用程序连接到服务器,获取消息并将其保存在数据库(coredata)中。 If the messages already exist, doesnt do anything and if they dont, add them to the database. 如果消息已经存在,则不执行任何操作;如果不存在,则将它们添加到数据库中。

I'm thinking some ways to do it but I don't know exactly what to do. 我正在考虑一些方法,但我不知道该怎么做。 Any help? 有什么帮助吗? Thanks in advance 提前致谢

I would recommend using Restkit framework http://restkit.org 我建议使用Restkit框架http://restkit.org
Reskit provides integration with Core Data. Reskit提供与Core Data的集成。

Pros of using Restkit: 使用Restkit的优点:
- Combines HTTP request/responses API, along with object mapping, offline/caching support with Core Data, all in one framework -将HTTP请求/响应API以及对象映射,脱机/缓存支持与Core Data结合在一起,全部集成在一个框架中
- Object Mapping means that you're writing clean code, you define your classes and how they map to the JSON attributes, then you GET/POST/DELETE with few lines of code after that -对象映射意味着您正在编写简洁的代码,定义类以及它们如何映射到JSON属性,然后在执行GET / POST / DELETE之后只需几行代码
- Core Data support means that your projects can work offline, data is sync when working online, but persistent when you need it offline -核心数据支持意味着您的项目可以离线工作,在线工作时数据是同步的,但是当您离线时数据是持久的
- The framework is well maintained -框架维护良好

Cons: 缺点:
- Works only with JSON REST APIs -仅适用于JSON REST API
- There can be a steep learning curve for some aspects -在某些方面可能会有陡峭的学习曲线
- Can be challenging if you work with REST APIs that are not completely 'standard' -如果您使用的不是完全“标准”的REST API,可能会遇到挑战

The simplest way is to add a guid attribute (an identifier of type NSString , for example) to the entity you are interested in and check for that guid when you import data. 最简单的方法是将guid属性(例如,类型为NSString的标识符)添加到您感兴趣的实体,并在导入数据时检查该guid。

Here, you have two ways: let the server generate the guid for you or implement your own algorithm in the client side (iPhone, iPad, etc.). 在这里,您有两种方法:让服务器为您生成Guid或在客户端(iPhone,iPad等)实现自己的算法。 In both cases you need to be sure the guid is unique for each message. 在这两种情况下,您都需要确保每个消息的GUI都是唯一的。

So, for example, suppose the server generates the messages (and each message has its own guid). 因此,例如,假设服务器生成了消息(每个消息都有自己的GUID)。 When you import data you also save the guid for each message object. 导入数据时,还要保存每个消息对象的GUID。 If you have already a message with a specific guid, you don't add it, otherwise you add it. 如果您已经有带有特定GUID的消息,则不要添加它,否则就添加它。 This could be done using the Find-or-Create pattern (see Implementing Find-or-Create Efficiently ). 可以使用“ 查找或创建”模式来完成此操作(请参阅有效地实现查找或创建 )。

Hope that helps. 希望能有所帮助。

This is simple, it took me sometime to learn this, I use it in most of my apps. 这很简单,我花了一些时间来学习它,我在大多数应用程序中都使用了它。

First you need an ID of the fetched item, for example messageID. 首先,您需要获取的项目的ID,例如messageID。 When you fetch the JSON with all the items, for example using AFNetworking, you're going to receive an array of objects in NSDictionaries. 当您使用所有项目(例如,使用AFNetworking)获取JSON时,您将在NSDictionaries中收到一个对象数组。

Before parsing the item load all the IDs of your stored items in a NSMutableDictionary (key => messageID, value objectID, this is related to the Core Data fault). 在解析项目之前,将存储的项目的所有ID加载到NSMutableDictionary中(键=> messageID,值objectID,这与Core Data故障有关)。

Don't forget to init the NSMutableArray somewhere: 不要忘记在某个地方初始化NSMutableArray:

_dictionaryOfEventIDAndObjectID = [NSMutableDictionary dictionary];

- (void)prepareDictionaryOfMessageIDs
{
    [self.dictionaryOfEventIDAndObjectID removeAllObjects];

    NSError *error = nil;
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:@"Message"];
    [fetchRequest setResultType:NSDictionaryResultType];
    NSExpressionDescription *objectIDDescription = [[NSExpressionDescription alloc] init];
    objectIDDescription.name = @"objectID";
    objectIDDescription.expression = [NSExpression expressionForEvaluatedObject];
    objectIDDescription.expressionResultType = NSObjectIDAttributeType;
    [fetchRequest setPropertiesToFetch:@[objectIDDescription, @"messageID"]];

    NSArray *objectsDict = [self.managedObjectContext executeFetchRequest:fetchRequest error:&error];
    for (NSDictionary *objectDict in objectsDict) {
        [self.dictionaryOfMessageIDAndObjectID setObject:[objectDict valueForKeyPath:@"objectID"] forKey:[objectDict valueForKeyPath:@"messageID"]];
    }
}

Then in the fetched data completion block just add something like this: 然后在获取的数据完成块中添加以下内容:

    for (NSDictionary *objectDict in objectsDict) {

        NSString *fetchedID = [objectDict objectForKey:@"id"];

        if ([self.dictionaryOfMessageIDAndObjectID objectForKey:fetchedID]) {
            continue;
        }

        [self parseMessageFromDictionary:objectDict];
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM