我关注NSObject:
@interface finalObject : NSObject
@property NSString *name;
@property NSString *image;
我在我的ViewController中声明这样:
finalArray = [[NSMutableArray alloc] init];
object = [finalObject new];
然后我将thename和图像循环到object.name和object.image中,并将此对象添加到名为finalArray的NSMutableArray中。
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName attributes:(NSDictionary *)attributeDict {
if ([elementName isEqualToString:@"language"]) {
thename = attributeDict[@"name"];
theimage = attributeDict[@"image"];
theId = attributeDict[@"id"];
object.name = thename;
object.image = theimage;
NSArray *cols = @[thename, theimage, theId ];
[finalArray addObject:object];
[rows addObject: cols];
}
现在我需要我的searchbar.text来搜索finalarray,我正在使用这种方法:
-(void) searchThroughdata {
self.filteredArray = nil;
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF contains [cd] %@",self.searchBar.text];
self.filteredArray = [[finalArray filteredArrayUsingPredicate:predicate] mutableCopy];
}
问题是finalArray在:
[[finalArray filteredArrayUsingPredicate:predicate]
应该只包含名称而不包含图像。我怎么能这样做?
目前我收到此错误:
'NSInvalidArgumentException', reason: 'Can't use in/contains operator with collection
<finalObject: 0x8c4f910> (not a collection)'
我尝试将SELF.name添加到“SELF contains [cd]%@”
答案 0 :(得分:0)
问题是finalArray ...应该只包含名称和 不是图像
你不能用谓词做到这一点。您可以在“name”属性上过滤数组 其元素:
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name contains [cd] %@",self.searchBar.text];
NSArray *filteredArray = [finalArray filteredArrayUsingPredicate:predicate];
然后,如有必要,创建一个只包含对象名称的新数组:
NSArray *filteredNames = [filteredArray valueForKey:@"name"];
另请注意,如上所述,您的代码只会创建单个对象, 它被反复修改并添加到数组中。 由于数组将指针保存到其元素中,因此您将以数组结尾 相同的对象。
创作应该转移到
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName attributes:(NSDictionary *)attributeDict {
if ([elementName isEqualToString:@"language"]) {
thename = attributeDict[@"name"];
theimage = attributeDict[@"image"];
theId = attributeDict[@"id"];
FinalObject *object = [FinalObject new];
object.name = thename;
object.image = theimage;
[finalArray addObject:object];
// ...
}
}
更新:如果我正确理解您的评论,则不应创建数组 仅包含名称。只需将过滤后的数组创建为
即可NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name contains [cd] %@",self.searchBar.text];
NSArray *filteredArray = [finalArray filteredArrayUsingPredicate:predicate];
然后,在cellForRowAtIndexPath
中,您可以访问对象属性,例如:
FinalObject *object = filteredArray[indexPath.row];
cell.textLabel.text = object.name;
// ... do something with object.image ...