The IOS UI Learning tutorial distinguishes between NSBundle and Nsurl (reading files, writing files) _ios

Source: Internet
Author: User

The example of this article distinguishes NSBundle and Nsurl, and realizes the following contents

In the project to add a file, this routine is added to the Aa.txt, the contents of the file for Baidu: Www.baidu.com, now to use NSBundle and Nsurl respectively to get content, the code is as follows:

  read the contents of the file
//  Method 1: Read
  nsstring *pathbundle by file path = [[NSBundle mainbundle]pathforresource:@ ' AA ' OfType : @ "TXT"];
  NSString *outstringbundle = [NSString stringwithcontentsoffile:pathbundle encoding:nsutf8stringencoding Error:nil];  Method 2: Follow the URL to read
  nsurl *pathurl = [[NSBundle mainbundle]urlforresource:@ ' AA ' withextension:@ ' txt ' subdirectory : nil];
  NSString *outstringurl = [NSString stringwithcontentsofurl:pathurl encoding:nsutf8stringencoding Error:nil];
  
  NSLog (@ "%@\n////////\n%@", Outstringbundle,outstringurl);

The output results are as follows:

2016-03-30 14:48:02.939 sand box mechanism and file path [11,786:518,929] Baidu: www.baidu.com
 ////////
 Baidu: www.baidu.com

Write to File:

Create a new file first:

NSString *newpath = [NSString stringwithformat:@ "%@/documents/new", Nshomedirectory ()];  First, the file path and filename are defined well
   nsstring *newfile = [NSString stringwithformat:@ "%@/new.mp3", NewPath];  Create a file using Createfileatpath
   [[Nsfilemanager defaultmanager]createfileatpath:newfile Contents:nil attributes : nil];
   NSLog (@ "%@", NewPath);

After reading and writing:

  write to file
//  1, first read data
  nsdata *data = [[NSData alloc]initwithcontentsoffile:pathbundle];
  NSLog (@ "%@", data);  2. Writes the read data to the sandbox file, newfile the mp3 file
  [data writetofile:newfile Atomically:yes] created in the sandbox file above;

Through a brief example for everyone to distinguish NSBundle and nsurl, I hope to help you learn.

Related Article

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.