Obj-c Programming 15[cocoa Instance 03]:MVC and archiving example

Source: Internet
Author: User

The previous it introduced the archive and the file, and here we actually apply it to a simple code, which is supported by the opening and saving of a multi-document application. In addition here to introduce the idea of MVC, this in any language will have, it is a design idea, can be summarized as a program consists of 3 parts:

1 mode: Is the data support of the program;

2 views: is the presentation support of the program;

3 Control: Connection mode and view, the program as a whole;

The Cocoa Framework provides very good support for MVC, and you can only write very little code to complete the MVC binding of a program. In the following example, I generate a multi-document-based program that uses the Nsarraycontroller class as the controller whose data source is Nsarray, where each element is described by the class person I define, and the Tab_view in the main window as the outlets in the main class. , the main class is document, which derives from NSDocument to support each document window in multiple documents.


Add and Remove buttons are bound to the add and remove methods in Nsarraycontroller, and the two columns of the Tab_view control are bound to the 2 properties in the Person class, respectively. Each row is naturally a person object in the Everyone array. The representation of the data in each view (Tab_view) is connected by the controller to the pattern, and the change of the view content (via the Add and Remove buttons) also leads to changes in the pattern data, and the change of the pattern itself (through the Read file operation) also updates the display of the view. This guarantees the independence of views and patterns: patterns can be displayed on other views, and views can be bound to other patterns.

Finally, the use of archiving to achieve the program's Save and open function, but also basically did not write a few lines of code, and save the file is automatically bound with our program, if double-click the file, will automatically open with our app Oh, it is very convenient. For details, see the code:

  document.h//  mac_doc////  Created by kinds on 14-7-7.//  Copyright (c) 2014 kinds. All rights reserved.//#import <Cocoa/Cocoa.h> @interface document:nsdocument{iboutlet nstableview *tab_view; Nsmutablearray *persons;} -(void) Setpersons: (Nsmutablearray *) ary; @end

document.m//mac_doc////Created by kinds on 14-7-7.//Copyright (c) 2014 kinds. All rights reserved.//#import "Document.h" @interface document () @end @implementation Document-(Instancetype) in    it {self = [super init];    if (self) {//ADD your subclass-specific initialization here.persons = [[Nsmutablearray alloc]init]; } return self;} -(void) Setpersons: (Nsmutablearray *) ary{if (ary = = persons) return;persons = ary;} -(void) windowcontrollerdidloadnib: (Nswindowcontroller *) Acontroller {[Super windowcontrollerdidloadnib:                            Acontroller];                            Add any code here, needs to is executed once the Windowcontroller has loaded the document ' s window. }+ (BOOL) autosavesinplace {return YES;} -(NSString *) windownibname {//Override returning the nib file name of the document//If you need for use a subclass of NS Windowcontroller or if your document supports multiple nswindowcontrollers, you should remove the This method and ovErride-makewindowcontrollers Instead.return @ "Document";} -(NSData *) Dataoftype: (NSString *) name error: (Nserror *) Out_err {//Insert code here to write your document to data of T He specified type. If Outerror! = NULL, ensure that you create and set a appropriate error when returning nil.//can also choose Ride-filewrapperoftype:error:,-writetourl:oftype:error:, Or-writetourl:oftype:forsaveoperation:o RiginalContentsURL:error:instead. [[Tab_view window] Endeditingfor:nil];return [Nskeyedarchiver archiveddatawithrootobject:persons];} -(BOOL) Readfromdata: (NSData *) data ofType: (NSString *) name error: (Nserror *) Out_err {//Insert code here to read your do Cument from the given data of the specified type. If Outerror! = NULL, ensure that you create and set a appropriate error when returning no.//can also choose to Overr ide-readfromfilewrapper:oftype:error:or-readfromurl:oftype:error:instead.//If You override either of these, you shoul D also Override-isentirefileloAded to return NO if the contents is lazily loaded. Nsmutablearray *new_ary = nil, @try {new_ary = [nskeyedunarchiver unarchiveobjectwithdata:data];} @catch (NSException *e) {NSLog (@ "exception =%@", e); if (out_err) {nsdictionary *d = [nsdictionary dictionarywithobject: @ "   Data is corrupted! " Forkey:nslocalizedfailurereasonerrorkey];*out_err = [Nserror errorwithdomain:nsosstatuserrordomain code:unimpErr USERINFO:D];} return NO;} [Self Setpersons:new_ary];return YES;} @end

  person.h//  mac_doc////  Created by kinds on 14-7-7.//  Copyright (c) 2014 kinds. All rights reserved.//#import <Foundation/Foundation.h> @interface person:nsobject <nscoding>{nsstring * Name;float Exp_raise;} @property (readwrite,copy) nsstring *name; @property (readwrite) float exp_raise; @end

  person.m//  mac_doc////  Created by kinds on 14-7-7.//  Copyright (c) 2014 kinds. All rights reserved.//#import "Person.h" @implementation person@synthesize name,exp_raise;-(ID) Initwithcoder: ( Nscoder *) coder{self = [Super Init];if (self) {name = [coder decodeobjectforkey:@ "name"];exp_raise = [coder decodefloatforkey:@ "Exp_raise"];} return self;} -(void) Encodewithcoder: (Nscoder *) coder{[coder encodeobject:name forkey:@ "name"];[ Coder encodefloat:exp_raise forkey:@ "Exp_raise"];} -(ID) init{self = [Super Init];if (self) {exp_raise = 0.05;name = @ "No_name";} return self;} -(void) Setnilvalueforkey: (NSString *) key{if ([Key isequaltostring:@ "Exp_raise"]) Self.exp_raise = 0.0;else[super Setnilvalueforkey:key];} @end

The program execution interface is as follows:


We can also set the icon and extension of the private archive file, such as:



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.