简体   繁体   中英

Filter NSArray of custom objects

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;
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"userId = %@", myContact.userId];
NSArray *filteredArray = [contacts filteredArrayUsingPredicate:predicate];

Is this what you are looking for?

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

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
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM