Question: How To Match object value of NSSet in CoreData?

Question

How To Match object value of NSSet in CoreData?

Answers 1
Added at 2016-12-29 05:12
Tags
Question

I Have Made One Core Data ONE TO MANY Relationships. A person can have multiple Bank’s Accounts.

Now

I have add Person and bank account linked with person.

Code is

@synthesize setContainer,textField;

- (void)viewDidLoad {
    [super viewDidLoad];
    self.setContainer = [[NSMutableSet alloc]init];
    appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];

    NSEntityDescription *entityPerson = [NSEntityDescription entityForName:@"Person" inManagedObjectContext:appDelegate.managedObjectContext];
    NSManagedObject *newPerson = [[NSManagedObject alloc]initWithEntity:entityPerson insertIntoManagedObjectContext:appDelegate.managedObjectContext];
    [newPerson setValue:@"Steve" forKey:@"name"];
    [newPerson setValue:@"UK" forKey:@"address"];
    [newPerson setValue:@123456 forKey:@"mobile_no"];

    NSEntityDescription *entityAccount = [NSEntityDescription entityForName:@"Account" inManagedObjectContext:appDelegate.managedObjectContext];
    NSManagedObject *newaccount = [[NSManagedObject alloc]initWithEntity:entityAccount insertIntoManagedObjectContext:appDelegate.managedObjectContext];
    [newaccount setValue:@98765432100 forKey:@"acc_no"];
    [newaccount setValue:@"Saving" forKey:@"acc_type"];
    [newaccount setValue:@1000000 forKey:@"balance"];

    // Add Address to Person
   setContainer = [newPerson mutableSetValueForKey:@"person"];
    [self.setContainer addObject:newaccount];
    NSLog(@"%@",self.setContainer);  // Save Managed Object Context
    NSError *error = nil;
    if (![newPerson.managedObjectContext save:&error]) {
        NSLog(@"Unable to save managed object context.");
        NSLog(@"%@, %@", error, error.localizedDescription);
    }

My Question is

When I type My mobile Number on Text Field and press button "Check Your Balance" ,My Balance should be Print In Log which , I have entered in Core Data value.

Image is

enter image description here

OutPut

enter image description here

enter image description here

Answers
nr: #1 dodano: 2016-12-29 06:12

You can use NSPredicate to fetch the entity based on a selected filter, on your case the Phone number

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"mobile_no = %@",phoneNumber];

NSFetchRequest *fetchRequest = [NSFetchRequest new];
[fetchRequest setPredicate:predicate];
NSError *error;
NSArray *result = [managedObjectContext executeFetchRequest:fetchRequest error:&error];

Based on this, you can perform the computation of amount if the user has multiple bank account since you already have all the details (assuming that he uses the same phone number on all his bank accounts)

Here is the documentation on NSPredicate

A good cheat sheet as well can be found here

Source Show
◀ Wstecz