The NSData class provides a convenient way to wrap binary data, such as the content of a text file or an image; and treat it as an NSData object.

nsdata_object

NSData’s two primitive methods bytes and length provide the basis for all the other methods in its interface. The bytes method returns a pointer to the bytes contained in the data object. length returns the number of bytes contained in the data object.

To practice source code presented in this lesson, you should download and unzip this file.
project_icon_codepractice
Launch the project (CodePractice.xcodeproj) and enter code in the viewController.m file’s buttonTapped method, then click the “Click Me” button to execute the method’s code.

Here is how you’d create and initialize a NSData object with text data, then save it in a text file in the Downloads directory.

// Declare an NSData object
NSData *textData;

// Initialize object
textData = [NSString stringWithFormat:@"%@",
@"What is a Class? A class is a blueprint or template that defines properties (data or attribute) and methods (operations or behavior. Think of a class as a cookie cutter. When you create a class in Objective-C, you define its properties (data) and methods (operations) and name its supper class. A method perform a specific task; for example, create book, delete book."];

// Save the textData object's data in text file
[textData writeToFile:@"/Users/your-name/Downloads/testfile.txt" atomically: YES];

// Display success message
self.outputBox.text = @"Text saved in the Downloads/testfile.txt file.";

Output
Text saved in the Downloads/testfile.txt file.

To verify that the text file was saved in the Downloads folder, use Finder to go to the folder. Once there, you should see the file listed there as shown in this snap shot.

Open the testfile.txt file in your favorite text editor; such as TextMate, and you will see text you assigned in the NSData object, textData.
nsdata_fig1
If you were to change content assign to the textData object and run the app again, existing content stored in the text file will be overwritten.

No Responses

Leave a Reply