Deep Dive into cocoa core data (3)-use binding
Luo chaohui (http://blog.csdn.net/kesalin)
CC license. For more information, see Source
We have explained the core data framework and manually compiled code to demonstrate how core data works. Next we will demonstrate how to use core data with xcode's powerful visual editing and cocoa key-value encoding and binding mechanism. With the powerful tools mentioned above, in this example, we do not need to write nsmanagedobjectmodel code or nsmanagedobjectcontext, and the Engineering Template has done these things for us.
The example to be completed today has two entity: studententity and classentity, each with an attribute named name. Studententity is associated with classentity through a relationship named inclass, and classentity also has a relationship named students associated with studententity, which is a one-to-many relationship. In addition, classentity has a relationship named monitor.
Associated with studententity, indicating the shift leader.
Download Code: Click here to download
The final result is as follows:
The following example is completed step by step:
1. Create a project:
Create a cocoa application named maccoredata and check "create document-based application" and "use core data". Here the core data and document engineering templates are used to simplify code writing.
2. classification file:
Create SRC and res groups under maccoredata, drag mydocument. h and mydocument to SRC, and drag other XIB and xcdatamodeld to res. Classifying files is a good habit, especially for large projects. Classify the files later ~~
3. Create an entity:
In the project, we can see the file named mydocument. xcdatamodeld. Its suffix indicates that this is a core data model file, and the framework reads the model file to generate the model. Next we will select this file and add two entities to it. Click Add entity below to add two new entity: classentity and studententity.
Add a string attribute named name to studententity, set its default value to student A, and check the status before optional;
Add a string attribute named name to classentity, set its default value to class XX, and check the status before optional;
The optional option indicates whether the attribute is optional. The name is required here.
Add a relationship named inclass pointing to classentity to studententity. The inverse column can be selected only after classentity has been added with a reverse relationship;
Add a relationship named students pointing to studententity to classentity. In the inverse column, inclass indicates that this is a bidirectional relationship. Check to-learn relationship because a class can have multiple students, this is a one-to-multiple relationship. After setting, we can set the inverse of the inclass relation of studententity to students.
Then add a relationship named monitor pointing to studententity to classentity to indicate the shift leader.
4. Generate the nsmanagedobject class:
Select studententity, and click File> New File… in the menu ..., After adding core data-> nsmanagerobject subclass, xcode will automatically generate studententity. h and studententity. M files for us. Remember to drag these two files to the SRC group. Let's take a look at the content in the two files:
Studententity. h
#import <Foundation/Foundation.h>#import <CoreData/CoreData.h>@class ClassEntity;@interface StudentEntity : NSManagedObject {@private}@property (nonatomic, retain) NSString * name;@property (nonatomic, retain) ClassEntity * inClass;@end
Studententity. m
#import "StudentEntity.h"#import "ClassEntity.h"@implementation StudentEntity@dynamic name;@dynamic inClass;@end
In the previous manual code example, we compile the run nsmanagedobject code by ourselves. Now, xcode has automatically generated the code for US based on the description of the model file. Sometimes the automatically generated code does not necessarily meet our needs, so we have to modify the code. For example, for classentity, the class leader can only be a member of its students, if we remove the student in students, the class leader should be empty.
Select classentity and repeat the preceding steps to automatically generate classentity. h and classentity. M. Next we will modify classentity. m as needed.
Add the following code at the beginning of-(void) removestudentsobject :( studententity *) value:
if (value == [self monitor]) [self setMonitor:nil];
Add the following code at the beginning of-(void) removestudents :( nsset *) value:
if ([value containsObject:[self monitor]]) [self setMonitor:nil];
In this way, when we delete a student in students, we will check whether the student is the squad leader. If so, we will leave the class leader empty.
5. The UI is generated below:
Here, we use the view switch method to display the student and class interfaces. Therefore, we need the main interface, class and student interfaces.
Add a popup button and an nsbox to mydocument. XIB. And delete the menu item in the popup control, because we need to add the class and student item through code.
Then add two new empty XIB files in Res: studentview. XIB and classview. XIB, respectively drag a m View to the two XIB files, and then add related controls in the view to form the UI. Remember to set the number of columns of two tableviews in classview to 1, and drag a popupbuttoncell to the class column in studentview. The effect is as follows:
6. Add viewcontroller:
Next we create viewcontroller to reload the XIB file in the program, display and switch the view. To facilitate the switching of views, we create a class inherited from nsviewcontroller named managedviewcontroller (remember not to create the XIB file corresponding to this class! Create a nsobject subclass and modify its parent class to nsviewcontroller), and then let studentviewcontroller and classviewcontroller inherit from it. The managedviewcontroller class code is as follows:
Managedviewcontroller. h
#import <Cocoa/Cocoa.h>@interface ManagedViewController : NSViewController {@private NSManagedObjectContext * managedObjectContext; NSArrayController * contentArrayController;}@property (nonatomic, retain) NSManagedObjectContext * managedObjectContext;@property (nonatomic, retain) IBOutlet NSArrayController *contentArrayController;@end
Managedviewcontroller. m
#import "ManagedViewController.h"@implementation ManagedViewController@synthesize managedObjectContext;@synthesize contentArrayController;- (void)dealloc{ self.contentArrayController = nil; self.managedObjectContext = nil; [super dealloc];}// deal with "Delete" key event.//- (void) keyDown:(NSEvent *)theEvent{ if (contentArrayController) { if ([theEvent keyCode] == 51) { [contentArrayController remove:nil]; } else { [super keyDown:theEvent]; } } else { [super keyDown:theEvent]; }}@end
In the above Code, we have an nsmanagedobjectcontext * managedobjectcontext pointer, which points to the nsmanagedobjectcontext object in the mydocument framework. As for the nsarraycontroller * contentarraycontroller, it is an iboutlet, associate it with the nsarraycontroller created in XIB, which will be discussed later. Contentarraycontroller is introduced here to enable Delete to delete records.
The classviewcontroller class code is as follows:
# Import "managedviewcontroller. H "@ interface classviewcontroller: managedviewcontroller {@ private} @ end # import" classviewcontroller. H "@ implementation classviewcontroller-(ID) Init {self = [Super initwithnibname: @" classview "Bundle: Nil]; If (Self) {[self settitle: @ "class"];} return self;}-(void) dealloc {[Super dealloc];} @ end
The code of the studentviewcontroller class is as follows:
# Import "managedviewcontroller. H "@ interface studentviewcontroller: managedviewcontroller {@ private} @ end # import" studentviewcontroller. H "@ implementation studentviewcontroller-(ID) Init {self = [Super initwithnibname: @" studentview "Bundle: Nil]; If (Self) {[self settitle: @ "student"];} return self;}-(void) dealloc {[Super dealloc];} @ end
In these two subclasses, we load the XIB file in the init method and set its title.
=== Last half =