Core Data Table Relationship and Fetchrequest

2019-09-21 19:36发布

问题:

I am developing one iPad application using storyboard and core data.I have no good idea about core data.I have 2 tables names A and B. Table a have 2 fields with names datacode and price.In table B there are two fields with names itemcode and text.Table A have set limit.

Table A

datacode price

p1 10

m1 17

p0 28

m3 20

w4 12

Table B

itemcode text

p0 car

p1 bus

m2 pen

m1 ball

p0 ban

r1 book

m3 pencil

n1 tv

w4 radio

The values in itemcode in tableB is the data code in the table A + some other value.i need to fetch the text values from the tableB based on the itemcodes which values corresponding to the datacode in the table A.I how can i fetch the text from B based on this criteria.

回答1:

First you need to create relationship between your both tables A and B. After that you have to fetch records based on you relations..... You will fetch your records like this....

NSMutableArray *arrObj = [[NSMutableArray alloc]init];
for(TableB *tblObj in [TableAObj relationWithTblB]){
      [arrObj addObject:tblObj];
}
NSLog(@"Your records related with tableA = %@",arrObj);


回答2:

You need to use predicate with your table A's datacode to table B's itemcode, like this:

NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];

NSEntityDescription *aEntity = [NSEntityDescription entityForName:@"TableA" inManagedObjectContext:moc];
[fetchRequest setEntity:BEntity];

NSArray* fetchResults = [moc executeFetchRequest:fetchRequest error:nil];

you will get all the objects of TableA. so if you have one - one relationship with TableB, you can directly access the all the attributes like:

TableA *tableAObject = fetchResults[i];
NSString * itemcode = tableAObject.tableBRelation.itemcode