面试题答案
一键面试关键类和方法
- CSSearchableItemAttributeSet类:用于定义要索引的数据的元数据属性集。
- CSSearchableItem类:用于创建可搜索的项目,通过传入包含元数据的CSSearchableItemAttributeSet实例。
- CSSearchableIndex类:用于与Spotlight索引进行交互,例如添加、删除或更新可搜索项目。主要方法有
indexSearchableItems:completionHandler:
用于将可搜索项目添加到索引中。
设置元数据示例
以下是一个简单示例,展示如何配置元数据:
#import <CoreSpotlight/CoreSpotlight.h>
#import <MobileCoreServices/MobileCoreServices.h>
// 创建CSSearchableItemAttributeSet实例
CSSearchableItemAttributeSet *attributeSet =
[[CSSearchableItemAttributeSet alloc] initWithItemContentType:(NSString *)kUTTypeText];
// 设置标题
attributeSet.title = @"示例标题";
// 设置描述
attributeSet.contentDescription = @"这是一个示例描述";
// 设置唯一标识符
NSString *uniqueIdentifier = @"com.example.app.uniqueID123";
// 创建CSSearchableItem实例
CSSearchableItem *searchableItem =
[[CSSearchableItem alloc] initWithUniqueIdentifier:uniqueIdentifier
domainIdentifier:@"com.example.app"
attributeSet:attributeSet];
// 获取CSSearchableIndex单例
CSSearchableIndex *searchableIndex = [CSSearchableIndex defaultSearchableIndex];
// 将项目添加到Spotlight索引
[searchableIndex indexSearchableItems:@[searchableItem] completionHandler:^(NSError * _Nullable error) {
if (error) {
NSLog(@"索引错误: %@", error);
} else {
NSLog(@"项目已成功添加到Spotlight索引");
}
}];
在上述示例中:
- 首先创建了
CSSearchableItemAttributeSet
实例,并根据数据类型设置了itemContentType
,这里假设是文本类型。 - 接着设置了
title
(标题)、contentDescription
(描述)。 - 定义了
uniqueIdentifier
(唯一标识符)。 - 使用上述信息创建了
CSSearchableItem
实例。 - 最后通过
CSSearchableIndex
的indexSearchableItems:completionHandler:
方法将项目添加到Spotlight索引中,并在完成处理程序中检查是否有错误。