使用Core Data时更新Spotlight搜索索引?

Ril*_*Dev 13 core-data ios swift corespotlight

我有一个Core Spotlight用于索引应用内容的应用.该应用程序还使用Core Data,并在创建NSManagedObject对象的详细信息时使用,CSSearchableItem然后添加到Spotlight Search Index.

事情是,我的印象是,没有方向参考下NSManagedObjectCSSearchableItem,所以当项目被添加到索引,它只是复制的细节.

以下是将项添加到索引的示例.

//Spotlight Index Search
// Create an attribute set to describe an item.

    let attributeSet = CSSearchableItemAttributeSet(itemContentType: kUTTypeData as String)

// Add metadata that supplies details about the item.

    attributeSet.title = "\(object.title)"
    attributeSet.contentDescription = "\(object.description)"

// Create an item with a unique identifier, a domain identifier, and the attribute set you created earlier.
    let item = CSSearchableItem(uniqueIdentifier: "1", domainIdentifier: "ObjectType", attributeSet: attributeSet)

// Add the item to the on-device index.
       CSSearchableIndex.defaultSearchableIndex().indexSearchableItems([item]) { error in

    if error != nil {
      print(error?.localizedDescription)
    }
      else {
      print("Item indexed.")
      }
    }
Run Code Online (Sandbox Code Playgroud)

将项目添加到索引后,所有项目都可通过聚光灯搜索进行搜索.appDelegate选择索引项时处理操作的函数.

因此,在我编辑或删除NSManagedObject应用程序内部之前,一切似乎都很好,因为Searchable Items Index索引中列出的项目不是最新的,并且仍然列出已删除/旧数据.

那么如何在CSSearchableIndex更新时NSManagedObject更新项目?

Rom*_*nko 6

如果您希望索引相关,则保持索引最新是至关重要的.每次使用Core Data执行此类操作时,都必须在索引中添加/删除项目.在从Core Data中删除之前,应使用以下方法从索引中删除项目.您还可以在CoreSpotlight文档中找到许多有用的信息.

- deleteSearchableItemsWithIdentifiers:completionHandler:


Kum*_*sav 2

您希望索引编制与项目删除同步。因此,请查找 CSSearchableIndex 类实现的这三个方法,以便在不再需要项目时删除它们。

  1. deleteAllSearchableItemsWithCompletionHandler(_:)
  2. deleteSearchableItemsWithDomainIdentifiers(_:completionHandler:)
  3. 删除SearchableItemsWithIdentifiers(_:completionHandler:)

就像这个例子一样,

CSSearchableIndex.defaultSearchableIndex().deleteSearchableItemsWithDomainIdentifiers(["tv-shows"]) { (error) -> Void in
    if error != nil {
        print(error?.localizedDescription)
    }
    else {
        // Items were deleted successfully
    }
}
Run Code Online (Sandbox Code Playgroud)