xcode过滤NSMutableArray元素的字符串内容
问题描述:
我想过滤包含“some”字符串的NSMutableArray元素。 ListArchives中填充了字符串元素,listFiles必须是过滤后的字符串元素。 XCode在最后发布的行中生成警报。什么做错了?任何其他方法来过滤NSMutableArray的元素?xcode过滤NSMutableArray元素的字符串内容
NSString *match = @"*some*";
listFiles = [[NSMutableArray alloc] init];
NSPredicate *sPredicate = [NSPredicate predicateWithFormat:@"SELF like[cd] %@", match];
listFiles = [listArchives filteredArrayUsingPredicate:sPredicate];
答
尝试使用的contains
代替like
,举例如下:
NSString *match = @"some";
listFiles = [[NSMutableArray alloc] init];
NSPredicate *sPredicate = [NSPredicate predicateWithFormat:@"SELF CONTAINS[cd] %@", match];
listFiles = [[listArchives filteredArrayUsingPredicate:sPredicate] mutableCopy];
答
如果你要搜索为 '喜欢' 操作。 比方说你有一个NSArray中有如下内容:
static int count = 0;
NSArray *results = [NSArray arrayWithObjects:@"What was", @"What is", @"What will", nil];
NSString *targetString = @"What"
for (NSString *strObj in results)
{
if ([strObj rangeOfString:targetString].location != NSNotFound){
NSLog (@"Found: %@", strObj);
count = count + 1;
}
}
NSLog(@"There were %d occurence of %@ string",count,targetString);
答
NSString *match = @"some";
listFiles = [[NSMutableArray alloc] init];
NSPredicate *sPredicate = [NSPredicate predicateWithFormat:@"SELF BEGINSWITH[c] %@", match];
listFiles = [listArchives filteredArrayUsingPredicate:sPredicate];
对于强大的搜索这可以成为你一些什么样的“Like”服务于SQL
。
好吧,似乎更好的选择。但仍然显示警告,“不可分割的指针类型分配给来自NSArray的NSMutableArray _strong”。所以如果我声明listFiles为NSArray解决它,但没有其他方式让listFiles也可变? – Jaume 2012-04-02 17:14:34
@Jaume这是因为编译器不知道已过滤的数组是否为'NSMutableArray'。试试这个,而不是最后一行:'[listFiles setArray:[listArchives filteredArrayUsingPredicate:sPredicate]];' – dasblinkenlight 2012-04-02 17:19:12
哦,当然可以!懒惰的评论从我自己:)我真的赞赏你的帮助! – Jaume 2012-04-02 17:23:23