MST

星途 面试题库

面试题:Objective-C中如何配置Core Spotlight索引属性集

在Objective-C里集成Core Spotlight内容搜索,需要配置索引属性集,请描述配置索引属性集的步骤,包括如何定义属性、设置属性类型等操作。
24.9万 热度难度
编程语言Objective-C

知识考点

AI 面试

面试题答案

一键面试
  1. 创建索引属性集

    • 在Xcode项目中,通过CoreSpotlight.framework来创建索引属性集。首先,创建一个CSSearchableIndexAttributeSet对象。例如:
    CSSearchableIndexAttributeSet *attributeSet = [[CSSearchableIndexAttributeSet alloc] initWithItemContentType:(NSString *)kUTTypeText];
    
    • 这里kUTTypeText表示内容类型为文本,根据实际情况可以替换为其他合适的UTI(Uniform Type Identifier),如kUTTypeImage表示图片类型。
  2. 定义属性

    • 文本属性
      • 假设要添加一个标题属性,可以这样做:
      [attributeSet setValue:@"示例标题" forKey:CSSearchableItemAttributeSetTitle];
      
      • 若要添加描述属性:
      [attributeSet setValue:@"这是一个示例描述" forKey:CSSearchableItemAttributeSetContentDescription];
      
    • 其他属性
      • 例如添加一个唯一标识符属性,用于唯一标识搜索结果:
      [attributeSet setValue:@"uniqueIdentifier123" forKey:CSSearchableItemAttributeSetIdentifier];
      
  3. 设置属性类型

    • CSSearchableIndexAttributeSet中的属性类型在定义时已经根据属性的key确定。例如,CSSearchableItemAttributeSetTitleCSSearchableItemAttributeSetContentDescription等属性对应的是文本类型。
    • 对于一些特殊属性,如日期属性,假设要添加一个创建日期属性:
    NSDate *creationDate = [NSDate date];
    [attributeSet setValue:creationDate forKey:CSSearchableItemAttributeSetCreationDate];
    
    • 这里CSSearchableItemAttributeSetCreationDate对应的就是日期类型,Core Spotlight会正确识别这种类型用于搜索和展示。
  4. 注册索引属性集

    • 当定义好属性集后,需要将其注册到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是领域标识符,用于组织搜索结果。