Filter NSArray of custom objects

不打扰是莪最后的温柔 提交于 2019-11-27 08:37:37

问题


I have a NSArray of Contact objects, we can call it contacts. Contact is a superclass, FacebookGroup and Individual are subclasses of Contact. FacebookGroup has a property called individuals which is a set of Individual objects.

I also have a NSArray of NSString objects, we can call it userIDs.

What I want to do is create a new NSArray from the existing contacts array that match the userIDs in userIDs.

So if contacts has 3 Contact objects with userID 1,2 and 3. And my userIDs has a NSString object 3. Then I want the resulting array to contain Contact which equals userID 3.

Contact.h

Contact : NSObject

FacebookGroup.h

FacebookGroup : Contact

@property (nonatomic, strong) NSSet *individuals;

Individual.h

Individual : Contact

@property (nonatomic, strong) NSString *userID;

回答1:


Is this what you are looking for?

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"userID IN %@", userIDs];
NSArray *filtered = [contacts filteredArrayUsingPredicate:predicate];



回答2:


NSPredicate *predicate = [NSPredicate predicateWithFormat:@"userId = %@", myContact.userId];
NSArray *filteredArray = [contacts filteredArrayUsingPredicate:predicate];



回答3:


i'm expecting you want like this once see this one,

 NSMutableArray *names = [NSMutableArray arrayWithObjects:@"one", @"two", @"three", @"four", nil];
    NSMutableArray *ids = [NSMutableArray arrayWithObjects:@"1", @"2", @"2", @"3", nil];
    NSMutableArray *array=[[NSMutableArray alloc]init];
    for(int i=0;i<[ids count];i++){
       if([[ids objectAtIndex:i] isEqualToString:@"2"])
           [array addObject:[names objectAtIndex:i]];
    }
    NSLog(@"%@",array);

O/P:-

(
    two,
    three
)


来源:https://stackoverflow.com/questions/16357314/filter-nsarray-of-custom-objects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!