当他们匹配一个或多个标准(kOption)时,我试图将对象返回到NSArray。 如果我有kOption1或kOption2或kOption3等等,我出来的代码效果很好,但如果我有kOption1和KOption2,它将只返回第一个。
我刚刚开始编程,我试图找出如何获得这个,而不必编写大量的if / else嵌套条件。或者这是我必须去的方式?
谢谢。
if ([[NSUserDefaults standardUserDefaults] boolForKey:kOption1]) {
return [BOTManagedObjectContext searchObjectsForEntity:@"Sede"
withPredicate:[NSPredicate predicateWithFormat:@"(idTipoSede != %d) AND (idTipoSede != %d)", kTipoSedePrivata, kTipoSedeDayOff]
sortKey:nil
sortAscending:NO];
} if ([[NSUserDefaults standardUserDefaults] boolForKey:kOption2]) {
return [BOTManagedObjectContext searchObjectsForEntity:@"Sede"
withPredicate:[NSPredicate predicateWithFormat:@"(idTipoSede = %d) OR (idTipoSede = %d) OR (idTipoSede = %d) OR (idTipoSede = %d) OR (idTipoSede = %d) OR (idTipoSede = %d)", kTipoSedeVenue, kTipoSedeArci, kTipoSedeSquat, kTipoSedeGalleria, kTipoSedeHouse, kTipoSedeFestival]
sortKey:nil
sortAscending:NO];
} if ([[NSUserDefaults standardUserDefaults] boolForKey:kOption3]) {
return [BOTManagedObjectContext searchObjectsForEntity:@"Sede"
withPredicate:[NSPredicate predicateWithFormat:@"(idTipoSede = %d) OR (idTipoSede = %d) OR (idTipoSede = %d) OR (idTipoSede = %d) OR (idTipoSede = %d) OR (idTipoSede = %d)", kTipoSedeVenue, kTipoSedeArci, kTipoSedeSquat, kTipoSedeGalleria, kTipoSedeHouse, kTipoSedePromoter]
sortKey:nil
sortAscending:NO];
} else {
return [something else...];
}
答案 0 :(得分:0)
使用NSMutableArray
,因为您必须返回多个元素
NSMutableArray *arr = [@[] mutableCopy];
if ([[NSUserDefaults standardUserDefaults] boolForKey:kOption1]) {
[arr addObject:[BOTManagedObjectContext searchObjectsForEntity:@"Sede"
withPredicate:[NSPredicate predicateWithFormat:@"(idTipoSede != %d) AND (idTipoSede != %d)", kTipoSedePrivata, kTipoSedeDayOff]
sortKey:nil
sortAscending:NO]];
}
if ([[NSUserDefaults standardUserDefaults] boolForKey:kOption2]) {
[arr addObject:[BOTManagedObjectContext searchObjectsForEntity:@"Sede"
withPredicate:[NSPredicate predicateWithFormat:@"(idTipoSede = %d) OR (idTipoSede = %d) OR (idTipoSede = %d) OR (idTipoSede = %d) OR (idTipoSede = %d) OR (idTipoSede = %d)", kTipoSedeVenue, kTipoSedeArci, kTipoSedeSquat, kTipoSedeGalleria, kTipoSedeHouse, kTipoSedeFestival]
sortKey:nil
sortAscending:NO]];
}
if ([[NSUserDefaults standardUserDefaults] boolForKey:kOption3]) {
[arr addObject: [BOTManagedObjectContext searchObjectsForEntity:@"Sede"
withPredicate:[NSPredicate predicateWithFormat:@"(idTipoSede = %d) OR (idTipoSede = %d) OR (idTipoSede = %d) OR (idTipoSede = %d) OR (idTipoSede = %d) OR (idTipoSede = %d)", kTipoSedeVenue, kTipoSedeArci, kTipoSedeSquat, kTipoSedeGalleria, kTipoSedeHouse, kTipoSedePromoter]
sortKey:nil
sortAscending:NO]];
}
if(something else) {
[arr addObject: [something else...]];
}
return arr;
并使用你得到的地方 arr [0]表示kOption1,arr [1]表示kOption2,arr [3]表示kOption3,依此类推,根据需要检查数组计数。