Reputation: 2952
I Have Made One Core Data ONE TO MANY Relationships. A person can have multiple Bank’s Accounts.
I have add Person and bank account linked with person.
@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);
}
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.
Upvotes: 2
Views: 275
Reputation: 2451
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
Upvotes: 1