我有一个朋友的NSMutableArray,其中包含Parse.com PFUser对象。每个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。感谢
如下修改ur代码。。使用NSMutableArray。。仅
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
}
}
使用谓词。。对象阵列的
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
希望它能帮助你。。!
使用NSPredcate,它应该看起来像这样:
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;
}
希望这能帮助
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF. username contains[c] %@", stringToCompare];
NSArray *filteredArray = [[NSArray alloc] initWithArray:[yourArray filteredArrayUsingPredicate:predicate]];
希望这对你有帮助。