2016-12-29 32 views
2

我做了一個核心數據一個關係。 一個人可以擁有多個銀行賬戶。如何在CoreData中匹配NSSet的對象值?

現在

我有加的人與一個人關聯的銀行帳戶。

代碼爲

@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:@0 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); 
    } 

我的問題是

當我輸入我的文本字段,並按下按鈕手機號碼「查詢餘額」,我的餘額應打印在登錄這,我已進入在覈心數據值。

圖片

enter image description here

輸出

enter image description here

回答

1

您可以使用NSPredicate來獲取基於選擇的過濾器上的實體,在你的情況下,電話號碼

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

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

基於此,如果用戶有多個銀行賬戶,因爲你已經把所有的細節(假設他使用同一個電話號碼上的所有他的銀行帳戶)

這裏是NSPredicate

的文檔,你可以執行金額的計算一個好的小抄也可以發現here

+0

謝謝,但我應該在哪裏把這個判斷方法,我怎麼可以比較,我從TextField和我的搜索帳戶的手機號碼輸入我的手機號碼?當您按下檢查您的平衡按鈕時是否有 – hd1344

+0

?檢查我的答案。它已經有了predicateWithFormat:phoneNumber可以代表你的'textField.text'。只要確保清理乾淨所有whiteSpaces。 – Joshua

+0

在最後一行發生錯誤:1)未知接收者'managedObjectContext';你的意思是'NSManagedObjectContext'? 2)沒有已知的類選擇方法'executeFetch:error:' – hd1344