Objective C学习笔记(三)

7,字符串和数字
  mac从文件中读取字符串
    NSString *filePathName = @"/Users/Shared/ScriptTestTempFile.js";
NSError *fileError;


NSString *textFileContents = [NSString stringWithContentsOfFile:filePathName 
                             encoding:NSASCIIStringEncoding error:&fileError];


if(fileError.code == 0)
{
   NSLog(@"textfile.txt contents: %@", textFileContents);
}
else
{
   NSLog(@"error(%ld): %@", fileError.code, fileError.description);
}


  iOS从文件读写字符串
      首先需要将文本文件拖放到Xcode中的Supporting Files目录下。当对话框弹出时,选中要将条目复制到
      目标分组目录的复选框。这么做可以确保文本文件会包含。在iOS中,需要获得指向包目录的引用。由于是动态
      目录路径,可以通过[[NSBundle mainBundle] resourcePath]获得指向所有资源文件所在目录的引用。
      接下来通过stringWithFormat:方法构建指向文本文件的引用.
      NSString *bundlePathName = [[NSBundle mainBundle] resoucePath];
      NSString *filePathName = [NSString stringWithFormat:@"%@/userFile.text", bundlePathName];
      其他同mac读写


  mac将字符串写到文件中:想字符串对象发送writeToFile:atomically:encoding:error:消息,文件路径名就
  会存储字符串对象中的内容。
    NSString *filePathName1 = @"/Users/Shared/test.txt";
    NSError *fileError1;
    
    NSString *textFileContents1 = @"Content generated from a Mac Program.Was it existed?";
    
    [textFileContents1 writeToFile:filePathName1 atomically:YES encoding:NSASCIIStringEncoding error:&fileError1];
    
    if(fileError1.code == 0)
    {
        NSLog(@"test.txt was written successfully with these contents: %@", textFileContents1);
    }
    else
    {
        NSLog(@"error(%ld): %@", fileError1.code, fileError1.description);
    }
  iOS将字符串写到文件中:
      同样的对于每个引用来说,文档目录是动态生成的,因此可以通过以下示列来获得之喜爱那个文档目录的引用。
      NSString *documentDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
      NSString *filePathName = [NSString stringWithFormat:@"%@/textfile.text", documentDirectory];
    其余步骤与mac写文件相同
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值