Search code examples
iosobjective-cnsarraynspredicate

NSPredicate on Array of Custom Object that contains another array of Custom Object


I have an array of objects called Student. Where every Student have another array of objects called Subject. Now I want to filter my Array of students with Subject Name. Example of Object is below:

@interface Student : NSObject

@property (nonatomic, assign) NSInteger studentId;
@property (nonatomic, strong) NSString  *name;
@property (nonatomic, strong) NSString  *class;
@property (nonatomic, strong) NSString  *section;
@property (nonatomic, strong) NSArray   *arraySubject;

@end

Where ArraySubject contains array of objects "Subject"

@interface Subject : NSObject

@property (nonatomic, assign) NSInteger subjectId;
@property (nonatomic, strong) NSString  *name;
@property (nonatomic, strong) NSString  *languageMedium;
@property (nonatomic, strong) NSString  *creditHours;

@end

What I want is to provide the "Subject Name" and filter my array of Students with that subject Name.

I hope I clears my question.


Solution

  • Try to use ANY for that.

    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"ANY arraySubject.name = %@", subjectName];
    NSArray *filterArray = [studentArray filteredArrayUsingPredicate:predicate];
    

    You can also use CONTAINS[c] if you doesn't want to match the exact subjectName with subject.

    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"ANY arraySubject.name CONTAINS[c] %@", subjectName];