简体   繁体   中英

IOS - objective C, How to read Core Data and store it into a mutable array

I have a set of core data with entity called PeronalInfo with attributes name, age gender, and nationality.

Eg

John, 25, Male, English

Sean, 65, Male, Indian

Jess, 46, Female, American

I need to store this core data as an array so I can do a check for anyone age over 30 and display all the attributes.

I have this so far:

- (NSManagedObjectContext *)managedObjectContext
{
    NSManagedObjectContext *context = nil;
    id delegate = [[UIApplication sharedApplication] delegate];
    if ([delegate performSelector:@selector(managedObjectContext)]) {
        context = [delegate managedObjectContext];
    }
    return context;
}


- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];

    [self preparePersonalInfo];
}

-(void)preparePersonalInfo
{
    // Fetch the devices from persistent data store
    NSManagedObjectContext *managedObjectContext = [self managedObjectContext];
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:@"PersonalInfo"];
    personalInfo = [[managedObjectContext executeFetchRequest:fetchRequest error:nil] mutableCopy];
}

- (void)viewDidLoad {
    [super viewDidLoad];

    NSMutableArray *personalInfoArray = [[NSMutableArray alloc] init];


    personalInfoArray = //This is where I need help to add the core data into this array

    //then I need to check if age is over 30
    //Then store the whole row of data as an array of an array to display it later

}

How do I do the commented section.

Thanks in advance!

If you only want a subset of the entries in Core Data, the right way to do it is to use a predicate on your fetch request so that you only fetch those entries. Something like

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"age > %@", 30];
fetchRequest.predicate = predicate;

That will filter the results of the fetch. You seem to already know how to convert the resulting NSArray into an NSMutableArray .

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