IPhone input/output stream asynchronously reads and writes data

Source: Internet
Author: User
Tags readfile

1. First, write data to the file.

Writefile. h

# Import <Foundation/Foundation. h> # import <uikit/uikit. h> @ Class notedb; @ interface writefile: nsobject <nsstreamdelegate> {// file address nsstring * parentdirectorypath; // output stream, write data nsoutputstream * asyncoutputstream; // nsdata * outputdata; // nsange outputrange; // data source notedb * anotedb;} @ property (nonatomic, retain) nsdata * outputdata; @ property (nonatomic, retain) notedb * anotedb; // write data-(void) write; @ end

Implementation file writefile. m

# Import "writefile. H" # import "notedb. H" @ implementation writefile @ synthesize outputdata, anotedb;-(ID) Init {self = [Super init]; If (! Self) {[self release]; return nil;} outputdata = [[nsdata alloc] init]; anotedb = [[notedb alloc] init]; return self;}-(void) write {// nslog (@ "% @", self. anotedb); // sandbox path nsarray * paths = nssearchpathfordirectoriesindomains (nsdocumentdirectory, nsuserdomainmask, yes); nsstring * documentsdirectory = [paths objectatindex: 0]; // The file name is note.txt nsstring * Path = [documentsdirectory stringbyappendingpathcomponent: @ "Note.txt"]; [asyncoutputstream release]; parentdirectorypath = path; // data source nsdata * tmpdata = [nskeyedarchiver archiveddatawithrootobject: Self. anotedb. notelist]; // self. outputdata = [[nsdata alloc] initwithdata: tmpdata]; self. outputdata = tmpdata; // where to start outputrange. location = 0; // create the file [[nsfilemanager defaultmanager] createfileatpath: parentdirectorypathcontents: Nil attributes: Nil]; // initialize the output stream asyncoutput Stream = [[nsoutputstream alloc] inittofileatpath: parentdirectorypath append: No]; // callback method, [asyncoutputstream setdelegate: Self]; // asynchronous processing, [asyncoutputstream scheduleinrunloop: [nsunloop currentrunloop] formode: nsdefaultrunloopmode]; // open the asynchronous output stream [asyncoutputstream open];}-(void) stream :( nsstream *) thestream handleevent :( nsstreamevent) streamevent {// nslog (@ "as"); nsoutputstream * outputstream = (nsoutput Stream *) thestream; bool shouldclose = no; Switch (streamevent) {Case nsstreameventhasspaceavailable: // read event {// buffer uint8_t outputbuf [1]; // length outputrange. length = 1; // put the data in the buffer [outputdata getbytes: & outputbuf range: outputrange]; // put the content in the buffer into the output stream [outputstream write: outputbuf maxlength: 1]; // determine whether data has been read if (++ outputrange. location = [outputdata length]) {shouldclose = yes;} break;} case nsstreameventer Roccurred: {// when an error occurs, nserror * error = [thestream streamerror]; If (error! = NULL) {uialertview * erroralert = [[uialertview alloc] initwithtitle: [error localizeddescription] Message: [error details] delegate: Nil cancelbuttontitle: @ "OK" failed: Nil]; [erroralert show]; [erroralert release];} shouldclose = yes; break;} case nsstreameventendencountered: shouldclose = yes;} If (shouldclose) {// when an error occurs or data is written, remove the thread from [outputstream removefromrunloop: [nsunloop currentrunloop] formode: nsdefaultrunloopmode]; // finally turn off the output stream [thestream close];}-(void) dealloc {[outputdata release]; [anotedb release]; [Super dealloc] ;}@ end

2. Second, reading data from files

Readfile. h

# Import <Foundation/Foundation. h> @ Class notedb; @ interface readfile: nsobject <nsstreamdelegate> {// path nsstring * parentdirectorypath; // asynchronous output stream nsinputstream * asyncinputstream; // read data nsmutabledata * resultdata; // return the de-data notedb * anotedb;} @ property (nonatomic, retain) notedb * anotedb; @ property (nonatomic, retain) nsmutabledata * resultdata; // start to read data-(void) read; // append the read data to resultdata-(void) appenddata :( nsdata *) _ data; //-(void) dataatnotedb; // return the Retrieved Data-(notedb *) getnotedb; @ end

Implement file readfile. m

# Import "readfile. H "# import" notedb. H "# import" notelist. H "# import" writefile. H "@ implementation readfile @ synthesize anotedb, resultdata;-(ID) Init {self = [Super init]; // anotedb = [[notedb alloc] init]; resultdata = [[nsmutabledata alloc] init]; return self;}-(void) read {// sandbox path nsarray * paths = nssearchpathfordirectoriesindomains (nsdocumentdirectory, nsuserdomainmask, yes ); nsstring * documentsdirectory = [Pat HS objectatindex: 0]; // file name nsstring * Path = [documentsdirectory stringbyappendingpathcomponent: @ "note.txt"];/* If (! [[Nsfilemanager defaultmanager] fileexistsatpath: path]) {// if it does not exist, create writefile * file = [[writefile alloc] init];} else {nslog (@ "note.txt file");} */[asyncinputstream release]; parentdirectorypath = path; // asynchronous input stream initialization, and assign the address asyncinputstream = [[nsinputstream alloc] initwithfileatpath: parentdirectorypath]; // sets the proxy (callback method, delegate) [asyncinputstream setdelegate: Self]; // sets the thread, add a thread and create a thread: as the name suggests, runloop is a non-stop loop that keeps removing CHEC K input [asyncinputstream scheduleinrunloop: [nsunloop currentrunloop] formode: nsdefaultrunloopmode]; // open the thread [asyncinputstream open];} // append data-(void) appenddata :( nsdata *) _ DATA {[resultdata appenddata: _ data];} // callback method, non-stop execution-(void) stream :( nsstream *) thestream handleevent :( nsstreamevent) streamevent {bool shouldclose = no; nsinputstream * inputstream = (nsinputstream *) thestream; // nslog (@ "as"); Switch (streameven T) {Case nsstreameventhasbytesavailable: {// read data // read byte length nsmaxlength = 128; // buffer uint8_t readbuffer [maxlength]; // read data from the output stream, read nsinteger bytesread = [inputstream read: readbuffer maxlength: maxlength]; // If the length is greater than 0, append the data if (bytesread> 0) {// read data in the buffer into data nsdata * bufferdata = [[nsdata alloc] initwithbytesnocopy: readbuffer length: bytesread freewhendone: No]; // append data [self appenddata: Buffer Data]; // release drop Data [bufferdata release];} break;} case nsstreameventerroroccurred: {// An error occurred while reading nserror * error = [thestream streamerror]; if (error! = NULL) {uialertview * erroralert = [[uialertview alloc] initwithtitle: [error localizeddescription] Message: [error details] delegate: Nil cancelbuttontitle: @ "OK" failed: Nil]; [erroralert show]; [erroralert release];} shouldclose = yes; break;} case nsstreameventendencountered: {shouldclose = yes; // data is returned after reading the data [self dataatnotedb]; [thestream close];} break;} If (shouldclose) {// when the file is read or an error is read, remove the thread [inputstream removefromrunloop: [nsunloop currentrunloop] formode: nsdefaultrunloopmode]; // close the stream [thestream close];}-(void) dataatnotedb {anotedb = nil; anotedb = [[notedb alloc] init]; anotedb. notelist = [nskeyedunarchiver unarchiveobjectwithdata: resultdata]; // nslog (@ "% @", anotedb);/* For (id tmp in anotedb. notelist. notearray) {nslog (@ "tmp = % @", TMP);} */}-(notedb *) getnotedb {return self. anotedb;}-(void) dealloc {[anotedb release]; [resultdata release]; [Super dealloc];} @ end

OK! This blog is my own exercise. I have not explained many things clearly. Please forgive me!

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.