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

时间:2015-02-23 09:38:11

标签: ios objective-c xcode nsmutablearray

我有一个包含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.谢谢

4 个答案:

答案 0 :(得分:0)

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

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

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

答案 1 :(得分:0)

试试这个,

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

希望这有帮助

答案 2 :(得分:0)

修改你的代码如下所示..使用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

希望它可以帮助你......!

答案 3 :(得分:0)

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

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

希望这会对你有所帮助。