我是Objective-C编码的Begginer,我需要一些关于NSPredicates的帮助。
我需要过滤(通过id_especie)我从Json文件解析的字典数组,并将数据检索到另一个数组。不幸的是,我得到的是一个空数组;
这是我的字典数组(id_especie表示species_id,id_raca表示breed_id):
{
"id_especie" = 1;
"id_raca" = 1;
raca = Afghanhound;
},
{
"id_especie" = 1;
"id_raca" = 2;
raca = "Airedale Terrier";
},
{
"id_especie" = 1;
"id_raca" = 3;
raca = Akita;
},...,
{
"id_especie" = 2;
"id_raca" = 47;
raca = "N/I";
},
{
"id_especie" = 2;
"id_raca" = 48;
raca = Siames;
},
{
"id_especie" = 3;
"id_raca" = 49;
raca = Periquito;
},
{
"id_especie" = 4;
"id_raca" = 50;
raca = Cobra;
},
{
"id_especie" = 4;
"id_raca" = 51;
raca = Lagarto;
},
{
"id_especie" = 5;
"id_raca" = 52;
raca = "Furao";
},
{
"id_especie" = 5;
"id_raca" = 53;
raca = Hamster;
},
{
"id_especie" = 6;
"id_raca" = 54;
raca = Outros;
}
这是我的代码:
·H
@property (nonatomic, strong) NSMutableArray *arrayBreedAndSpecies;
@property (nonatomic, strong) NSArray *filteredArray; //edited
的.m
NSError *errorLoad = nil;
NSURL *jsonUrl = [[NSURL alloc]initWithString:@"http://marcosdegni.com.br/petsistema/teste/raca.php"];
NSString *jsonString = [NSString stringWithContentsOfURL:jsonUrl encoding:NSUTF8StringEncoding error:&errorLoad];
if (!errorLoad) {
NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:nil];
self.arrayBreedAndSpecies = [[NSMutableArray alloc] initWithArray:jsonArray];
}
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"%@ = %@",@"id_especie", @"2"];
[self.filteredArray setArray: [self.arrayBreedAndSpecies filteredArrayUsingPredicate:predicate]];
NSLog(@"Filter: %@", self.filteredArray);
答案 0 :(得分:0)
这里只是一个猜测,因为这里没有一个有效的代码示例:
[self.filteredArray setArray: [self.arrayBreedAndSpecies filteredArrayUsingPredicate:predicate]];
如果self.filteredArray为零,那条线将什么都不做......我敢打赌你的意思是:
self.filteredArray = [self.arrayBreedAndSpecies filteredArrayUsingPredicate:predicate];
答案 1 :(得分:0)
好的,我注意到你的NSPredicate代码有一些错误:
1)谓词中的动态密钥路径应为%K
而不是%@
。
2)要检查数字值是否等于另一个,您需要使用==
而不仅仅是=
因此,代码的最后一部分应为:
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"%K == %i",@"id_especie", 2];
self.filteredArray = [NSArray arrayWithArray:[self.arrayBreedAndSpecies filteredArrayUsingPredicate:predicate]];
NSLog(@"Filter: %@", self.filteredArray);
我假设id_especie
属性是数字值。如果是字符串值,则可以使用谓词:[NSPredicate predicateWithFormat:@"%K MATCHES[cd] %@", @"id_especie", @"2"];
希望这有帮助