Data Model relationship of iOS CoreData development, ioscoredata
Next, in the previous article, we implemented a user entity. This time, we added a user information entity, which is associated with the user entity. The relationship is.
Create an entity UserInfo:
Add field:
The relationship between user information and users is established below:
This is an association between User and UserInfo. Next
Here I will explain it a little:
Name: Name
Properties: temporary link of the Transient. Optional (Optional) indicates that a User does not necessarily have UserInfo.
Destination: target table
Inverse
Delete Rule: Delete a Rule
Cascade: delete a User and delete UserInfo.
Deny: If UserInfo exists, the User cannot be deleted.
Nullify: Neither User nor UserInfo is deleted, but the association between them is deleted.
No Action: Haha
Type: 1:1 1: n, you know
Next is reverse Association.
Here Inverse corresponds to the above Inverse, second understanding ~
Then, the Code & Run will be regenerated.
Next, update our controller code. If you do not know the code, you can view the previous blog portal.
1-(void) insertToDB :( NSString *) username password :( NSString *) password 2 {3 User * u = (User *) [NSEntityDescription insertNewObjectForEntityForName: @ "User" inManagedObjectContext: self. cdContext]; 4 u. username = username; 5 u. password = password; 6 7 UserInfo * info = (UserInfo *) [NSEntityDescription insertNewObjectForEntityForName: @ "UserInfo" inManagedObjectContext: self. cdContext]; 8 info. age = @ 12; 9 info. sex = @ 1; 10 info. address = @ "China"; 11 12 u. userInfo = info; 13 info. user = u; 14 15 16 NSError * err; 17 if (! [Self. cdContext save: & err]) 18 {19 NSLog (@ "Error % @", err. localizedDescription, err. response); 20} 21 22} 23 24-(void) readFromDb25 {26 NSFetchRequest * fetch = [[NSFetchRequest alloc] init]; 27 NSEntityDescription * entity = [NSEntityDescription entityForName: @ "User" inManagedObjectContext: self. cdContext]; 28 [fetch setEntity: entity]; 29 // The limit is 30 [fetch setFetchLimit: 1]; 31 NSError * err; 32 NSArray * results = [self. cdContext executeFetchRequest: fetch error: & err]; 33 if (err) 34 {35 NSLog (@ "Error % @", err. localizedDescription, err. localizedFailureReason); 36 return; 37} 38 [results enumerateObjectsUsingBlock: ^ (User * _ Nonnull user, NSUInteger idx, BOOL * _ Nonnull stop) {39 NSLog (@ "---- username: % @ password: % @ address: % @ ", user. username, user. password, user. userInfo. address); 40}]; 41}
Run and see ~
This blog is over. I'm sure there will be some in the future. It's just a simple introduction ~