【问题标题】:Filter AFNetworking response过滤 AFNetworking 响应
【发布时间】:2025-12-13 07:10:01
【问题描述】:

我的 AFNetworking API 响应包含一个 json 对象“place”,它可以是“restaurant”或“store”。仅当地点对象包含关键字“store”时,我才想过滤响应以添加到 location_results 数组中

这是我的 AFNetworking 请求

  [[LocationApiClient sharedInstance] getPath:@"locations.json" parameters:nil                                     success:^(AFHTTPRequestOperation *operation, id response) {
        NSLog(@"Response: %@", response);
        NSMutableArray *location_results = [NSMutableArray array];
        for (id locationDictionary in response) {
            Location *location = [[Location alloc] initWithDictionary:locationDictionary];
            [location_results addObject:location]; 
        }
        self.location_results = location_results;
        [self.tableView reloadData];
    }
                                        failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                                            NSLog(@"Error fetching locations!");
                                            NSLog(@"%@", error);

                                        }];


}

我尝试添加这个

for (id locationDictionary in response) {
    Location *location = [[Location alloc] initWithDictionary:locationDictionary];
    if([[location objectForKey:@"place"] isEqualToString:@"Store"]) // Added this line
        [location_results addObject:location];

}

但我得到一个错误 - 'Location' 没有可见的@interface 声明选择器'objectForKey'

如何在[location_results addObject:location]; 之前过滤此回复?

【问题讨论】:

  • 你想使用KVC吗?如果是,请使用valueForKey: 而不是objectForKey:。因为objectForKey:NSDictionary 的方法。
  • 谢谢@VitaliyB 我想我会坚持使用 objectForKey 并使用我刚刚发布的答案。

标签: ios uitableview afnetworking


【解决方案1】:

我刚刚能够通过添加这一行来回答我的问题

self.location_results = [location_results filteredArrayUsingPredicate:
                                 [NSPredicate predicateWithFormat:@"(%K contains %@)",@"place" ,@"store"]];

  }
        self.location_results = location_results; //replaced this line
        [self.tableView reloadData];
    }

【讨论】: