自定義通訊錄,將模型數組中 `name` 字段單獨提取排序後重新賦值,導致名字與電話、郵箱等其他信息錯位不匹配。
// 錯誤做法
NSArray *names = [models valueForKey:@"name"];
NSArray *sortedNames = [names sortedArrayUsingSelector:@selector(localizedStandardCompare:)];
// 再嘗試按 sortedNames 重組模型 → 索引錯亂
// 正確做法:直接對模型數組排序,保持對象完整性
NSArray *sortedModels = [models sortedArrayUsingComparator:^NSComparisonResult(ContactModel *m1, ContactModel *m2) {
return [m1.name localizedStandardCompare:m2.name];
}];
// Swift 版
let sortedModels = models.sorted { $0.name.localizedStandardCompare($1.name) == .orderedAscending }
數據模型是不可分割的整體。任何排序、篩選、分組操作都應針對模型對象本身,而非拆解字段單獨操作。這也是 MVC/MVVM 中 Model 職責的體現。