面试题答案
一键面试-
创建索引属性集:
- 在Xcode项目中,通过
CoreSpotlight.framework
来创建索引属性集。首先,创建一个CSSearchableIndexAttributeSet
对象。例如:
CSSearchableIndexAttributeSet *attributeSet = [[CSSearchableIndexAttributeSet alloc] initWithItemContentType:(NSString *)kUTTypeText];
- 这里
kUTTypeText
表示内容类型为文本,根据实际情况可以替换为其他合适的UTI(Uniform Type Identifier),如kUTTypeImage
表示图片类型。
- 在Xcode项目中,通过
-
定义属性:
- 文本属性:
- 假设要添加一个标题属性,可以这样做:
[attributeSet setValue:@"示例标题" forKey:CSSearchableItemAttributeSetTitle];
- 若要添加描述属性:
[attributeSet setValue:@"这是一个示例描述" forKey:CSSearchableItemAttributeSetContentDescription];
- 其他属性:
- 例如添加一个唯一标识符属性,用于唯一标识搜索结果:
[attributeSet setValue:@"uniqueIdentifier123" forKey:CSSearchableItemAttributeSetIdentifier];
- 文本属性:
-
设置属性类型:
CSSearchableIndexAttributeSet
中的属性类型在定义时已经根据属性的key
确定。例如,CSSearchableItemAttributeSetTitle
和CSSearchableItemAttributeSetContentDescription
等属性对应的是文本类型。- 对于一些特殊属性,如日期属性,假设要添加一个创建日期属性:
NSDate *creationDate = [NSDate date]; [attributeSet setValue:creationDate forKey:CSSearchableItemAttributeSetCreationDate];
- 这里
CSSearchableItemAttributeSetCreationDate
对应的就是日期类型,Core Spotlight会正确识别这种类型用于搜索和展示。
-
注册索引属性集:
- 当定义好属性集后,需要将其注册到
CSSearchableIndex
中。首先获取CSSearchableIndex
的单例对象:
CSSearchableIndex *searchableIndex = [CSSearchableIndex defaultSearchableIndex];
- 然后使用以下方法注册属性集(假设
attributeSet
为已定义好的属性集):
[searchableIndex indexSearchableItems:@[ [[CSSearchableItem alloc] initWithUniqueIdentifier:@"itemID1" domainIdentifier:@"myDomain" attributeSet:attributeSet] ] completionHandler:^(NSError * _Nullable error) { if (error) { NSLog(@"索引注册错误: %@", error); } else { NSLog(@"索引注册成功"); } }];
- 这里
uniqueIdentifier
是搜索项的唯一标识符,domainIdentifier
是领域标识符,用于组织搜索结果。
- 当定义好属性集后,需要将其注册到