在数组中搜索对象并检查 NSString 字段是否匹配

Searching an array for an object and checking if a NSString field matches

我有一个包含 Parse.com 个 PFUser 对象的朋友的 NSMutableArray。每个 PFUser 都有一个 NSString 字段。我想在这个数组中搜索包含特定字符串的对象。到目前为止,我正在使用这个:

NSString username = "bob";
PFUser *user = [[PFUser alloc] init];

        for(PFUser *userItem in self.currentUser.friends) {

            if([user.username isEqualToString:username]) {

                user=userItem;
            }
        }

有更好的方法吗?这比使用 NSMutable 字典然后以这种方式提取对象慢得多吗?我的数组大小约为 100。谢谢

使用 NSPredicate,它应该看起来像这样:

  NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF.object.stringInsideObject LIKE %@", stringToCompare];

  NSArray *filteredArray = [[NSArray alloc] initWithArray:[yourArray filteredArrayUsingPredicate:predicate]];

试试这个,

- (PFUser *)filterUserObjectWithName:(NSString *)userName
{
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF.username == %@",userName];
    NSArray *results =  [self.currentUser.friends filteredArrayUsingPredicate:predicate];
    return results.count ? [results firstObject]: nil;
}

希望对您有所帮助

修改你的代码如下..使用 NSMutableArray..only

NSString username = "bob";
PFUser *user = [[PFUser alloc] init];

        for(PFUser *userItem in self.currentUser.friends) {
            //In your code it is written as user.username instead of userItem.username..check it..
            if([userItem.username isEqualToString:username]) {

                user=userItem;
                break;//exit from loop..Results in optimisation
            }
        }

使用 Predicate..of 对象数组

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", username];
NSArray *results = [self.currentUser.friends filteredArrayUsingPredicate:predicate];
PFUser *user=[[PFUser alloc]init];
user=[results objectAtIndex:0];//here is the object u need

希望对你有帮助..!

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF. username contains[c] %@", stringToCompare];

NSArray *filteredArray = [[NSArray alloc] initWithArray:[yourArray filteredArrayUsingPredicate:predicate]];

希望对您有所帮助。