Oc-nsfilehandle induction, let the object adhere to the Nscoding protocol, the object is stored in an array, and then by decoding the output

Source: Internet
Author: User

Person.m

#import "Person.h"


@implementation Person

Coding

-(ID) Initwithcoder: (nscoder *) adecoder{

self = [superinit];

if (self) {

Self. name = [[AdecoderDecodeobjectforkey:@ ' name ']copy]; //Copy not change

Self. age = [Adecoderdecodeintforkey:@ ' age '];

}

returnself;

}

decoding

-(void) Encodewithcoder: (nscoder *) acoder{

[Acoderencodeobject:self. name forkey:@ "name"];

[Acoderencodeint:self. Age forkey:@ "age"];

}


@end


Main.m

#import <Foundation/Foundation.h>


int Main (int argc,const Char * argv[]) {

@autoreleasepool {


nsstring * Path = [nshomedirectory()stringbyappendingpathcomponent: @ "Desktop/jereh.txt" ];

Nsfilemanager * manager = [nsfilemanagerdefaultmanager];

if (! [Manager Fileexistsatpath:p Ath]) {

[manager createfileatpath:p ath contents:nilattributes: nil ];

nsfilehandle * filehandle = [nsfilehandlefilehandleforwritingatpath:p Ath];

NSString * str = @ "Dsafas";

NSData * data = [str datausingencoding:nsutf8stringencoding];

[FileHandleseektoendoffile];

[FileHandle Writedata:data];

//1. writing an array to a file

nsarray * array = @[@ "Jack"@ "Jim"];

//[Array componentsjoinedbystring:@ "-"];

// Custom Induction

nsdata * data2 = [nskeyedarchiverarchiveddatawithrootobject: array];

[FileHandlewritedata:d ata2];

[FileHandleCloseFile];


}Else{

2. read it from the array

nsfilehandle * readhandle = [nsfilehandlefilehandleforreadingatpath:p Ath];

nsdata * data = [Readhandle availabledata];

nsarray * array = [nskeyedunarchiverunarchiveobjectwithdata:d ATA];

for (nsstring * tep in array) {

NSLog (@ "%@", TEP);

}

[ReadhandleCloseFile];

}

inductive

}

return 0;

}


Oc-nsfilehandle induction, let the object adhere to the Nscoding protocol, the object is stored in an array, and then by decoding the output

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.