【问题标题】:xcode filter NSMutableArray elements by string contentsxcode 按字符串内容过滤 NSMutableArray 元素
【发布时间】:2012-04-02 17:03:28
【问题描述】:

我想过滤包含“some”字符串的 NSMutableArray 元素。 ListArchives 填充了字符串元素,并且 listFiles 必须是过滤的。 XCode 在最后发布的行生成警报。做错了什么?还有其他过滤 NSMutableArray 元素的方法吗?

NSString *match = @"*some*"; 
listFiles = [[NSMutableArray alloc] init];

NSPredicate *sPredicate = [NSPredicate predicateWithFormat:@"SELF like[cd] %@", match];

listFiles = [listArchives filteredArrayUsingPredicate:sPredicate];

【问题讨论】:

    标签: iphone objective-c ios xcode cocoa-touch


    【解决方案1】:

    尝试使用contains而不是like,例如如下:

    NSString *match = @"some"; 
    listFiles = [[NSMutableArray alloc] init];
    
    NSPredicate *sPredicate = [NSPredicate predicateWithFormat:@"SELF CONTAINS[cd] %@", match];
    
    listFiles = [[listArchives filteredArrayUsingPredicate:sPredicate] mutableCopy];
    

    【讨论】:

    • 好的,似乎是更好的选择。但是仍然显示警告“从 NSArray 分配给 NSMutableArray _strong 的不兼容指针类型”。因此,如果我将 listFiles 声明为 NSArray 可以解决它,但没有其他方法可以让 listFiles 也可变?
    • @Jaume 这是因为编译器不知道过滤后的数组是NSMutableArray。试试这个而不是最后一行:[listFiles setArray:[listArchives filteredArrayUsingPredicate:sPredicate]];
    • 最后一行listFiles = [[listArchives filteredArrayUsingPredicate:sPredicate] mutableCopy]
    • @Nazir 谢谢!您可以随时提出修改建议 - 这通常比写评论要快。
    【解决方案2】:

    如果您想搜索为“喜欢”运算符。 假设您有一个包含以下内容的 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);
    

    【讨论】:

      【解决方案3】:
      NSString *match = @"some";
      listFiles = [[NSMutableArray alloc] init];
      NSPredicate *sPredicate = [NSPredicate predicateWithFormat:@"SELF BEGINSWITH[c] %@", match];
      listFiles = [listArchives filteredArrayUsingPredicate:sPredicate];
      

      对于强大的搜索,这可以为您提供一些“喜欢”在SQL 中提供的服务。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-01-10
        • 2020-03-07
        • 2018-03-25
        相关资源
        最近更新 更多