[Cocoa] core data of cocoa (3)-use binding

Source: Internet
Author: User

Deep Dive into cocoa core data (3)-use binding

Luo chaohui (http://www.cnblogs.com/kesalin)

This article follows the "signature-non-commercial use-consistency" creation public agreement

We have explained the core data framework and compiled it manually.CodeDemonstrate the operation process of core data. 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 viewcontrollerProgramTo 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.

 

=== The first half is complete. Check the second half. ===

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.