10,文件委托,以便操作文件。头部看起来像是这样。

@interface MyFileManager : NSObject

@property(strong)NSFileManager *fileManager;

@end

.m文件

#import "MyFileManager.h"

@implementation MyFileManager

@synthesize fileManager;

@end

可以在头部引入接口。

#import <Foundation/Foundation.h>

@interface MyFileManager : NSObject<NSFileManagerDelegate>

@property(strong)NSFileManager *fileManager;

@end

MyFileManager里面的可选方法。是否能复制

- (BOOL)fileManager:(NSFileManager *)fileManager shouldCopyItemAtPath:(NSString *)srcPath  toPath:(NSString *)dstPath{

if([dstPath hasPrefix:@"/Users/Shared/Book/Protected"]){

NSLog(@"We cannot copy files into the protected folder and so this file was not copied");

return NO;

}

else{

NSLog(@"We just copied a file successfully");

return YES;

}

}

重写初始化方法

- (id)init {

self = [super init];

if (self) {

self.fileManager = [[NSFileManager alloc] init];

self.fileManager.delegate = self;

}

return self;

}

在main.m里面使用刚刚创建的类。

#import <Foundation/Foundation.h>

#import "MyFileManager.h"

int main (int argc, const char * argv[])

{

@autoreleasepool {

MyFileManager *myFileManager = [[MyFileManager alloc] init];

NSString *protectedDirectory = @"/Users/Shared/Book/Protected";

NSString *cacheDirectory = @"/Users/Shared/Book/Cache";

NSString *fileSource = @"/Users/Shared/Book/textfile.txt";

NSString *fileDestination1 = @"/Users/Shared/Book/Protected/textfile.txt";

NSString *fileDestination2 = @"/Users/Shared/Book/Cache/textfile.txt";

NSError *error = nil;

NSArray *listOfFiles;

NSLog(@"Look at directories BEFORE attempting to copy");

listOfFiles = [myFileManager.fileManager contentsOfDirectoryAtPath:protectedDirectory

error:&error];

NSLog(@"List of files in protected directory (before):%@", listOfFiles);

listOfFiles = [myFileManager.fileManager contentsOfDirectoryAtPath:cacheDirectory

error:&error];

NSLog(@"List of files in cache directory (before):%@", listOfFiles);

//Attempt to copy into protected folder:

BOOL fileCopied1 = [myFileManager.fileManager copyItemAtPath:fileSource

toPath:fileDestination1

error:&error];

if(error)

NSLog(@"There was an error, %@.  fileCopied1 = %i", error, fileCopied1);

//Attempt to copy into cache folder:

BOOL fileCopied2 =  [myFileManager.fileManager copyItemAtPath:fileSource

toPath:fileDestination2

error:&error];

if(error)

NSLog(@"There was an error, %@.  fileCopied2 = %i", error, fileCopied2);

NSLog(@"Look at directories AFTER attempting to copy");

listOfFiles = [myFileManager.fileManager contentsOfDirectoryAtPath:protectedDirectory

error:&error];

NSLog(@"List of files in protected directory (after):%@", listOfFiles);

listOfFiles = [myFileManager.fileManager contentsOfDirectoryAtPath:cacheDirectory

error:&error];

NSLog(@"List of files in cache directory (after):%@", listOfFiles);

}

return 0;

}

此例子简单说明了委托方法的应用。

11,

使用文件或其他来源的数据。

组合字符串并写入文件。

NSUInteger length = 3;

char bytes1[length];

bytes1[0] = 'A';

bytes1[1] = 'B';

bytes1[2] = 'C';

char bytes2[length];

bytes2[0] = 'D';

bytes2[1] = 'E';

bytes2[2] = 'F’;

声明可变数组。

NSMutableData *mutableData = [[NSMutableData alloc] init];

可变数组有很多方法,具体参考手册。

下面是代码。

NSUInteger length = 3;

char bytes1[length];

bytes1[0] = 'A';

bytes1[1] = 'B';

bytes1[2] = 'C';

for (int i=0;i<sizeof(bytes1);i++)

NSLog(@"bytes1[%i] = %c", i, bytes1[i]);

char bytes2[length];

bytes2[0] = 'D';

bytes2[1] = 'E';

bytes2[2] = 'F';

for (int i=0;i<sizeof(bytes2);i++)

NSLog(@"bytes2[%i] = %c", i, bytes2[i]);

NSMutableData *mutableData = [[NSMutableData alloc] init];

[mutableData appendBytes:bytes1

length:length];

[mutableData appendBytes:bytes2

length:length];

NSLog(@"mutableData = %@", mutableData);

char *bytesFromData = (char *)[mutableData bytes];

for (int i=0;i<length*2;i++)

NSLog(@"bytesFromData[%i] = %c", i, bytesFromData[i]);

NSError *error = nil;

BOOL dataSaved = [mutableData writeToFile:@"/Users/Shared/Book/datadump.txt"

options:NSDataWritingAtomic

error:&error];

if(dataSaved)

NSLog(@"mutableData successfully wrote contents to file system");

else

NSLog(@"mutableData was unsuccesful in writing out data because of %@", error);

12,NSCache缓存数据。

比如创建一个ViewController类。

.h文件里面

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController

@property (strong) NSCache *cache;

@property (assign) BOOL regularLogo;

@property (strong) UIImageView *myImageView;

@property (strong) UIButton *loadImageButton;

- (void)presentImage;

@end

.m文件里面

#import "ViewController.h"

@implementation ViewController

-(void)viewDidLoad{

[super viewDidLoad];

//set up the cache

self.cache = [[NSCache alloc] init];

} @end

只要试图被激活就可以使用缓存。

下面是具体代码。

Listing 4-14. AppDelegate.h #import <UIKit/UIKit.h>

@class ViewController;

@interface AppDelegate : UIResponder <UIApplicationDelegate>

@property (strong, nonatomic) UIWindow *window;

@property (strong, nonatomic) ViewController *viewController;

@end

Listing 4-15. AppDelegate.m #import "AppDelegate.h"

#import "ViewController.h"

@implementation AppDelegate

@synthesize window = _window;

@synthesize viewController = _viewController;

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];

// Override point for customization after application launch.

self.viewController = [[ViewController alloc]

initWithNibName:@"ViewController" bundle:nil];

self.window.rootViewController = self.viewController;

[self.window makeKeyAndVisible];

return YES;

} @end

Listing 4-16. ViewController.h #import <UIKit/UIKit.h>

@interface ViewController : UIViewController

@property (strong) NSCache *cache;

@property (assign) BOOL regularLogo;

@property (strong) UIImageView *myImageView;

@property (strong) UIButton *loadImageButton;

- (void)presentImage;

@end

Listing 4-17. ViewController.m #import "ViewController.h"

@implementation ViewController

@synthesize cache, regularLogo, myImageView, loadImageButton;

-(void)viewDidLoad{

[super viewDidLoad];

//Change the view's background color to white

self.view.backgroundColor = [UIColor whiteColor];

//Load the regular logo first

self.regularLogo = YES;

//set up the cache

self.cache = [[NSCache alloc] init];

//Setup the button

self.loadImageButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];

self.loadImageButton.frame = CGRectMake(20, 415, 280, 37);

[self.loadImageButton addTarget:self

action:@selector(presentImage)

forControlEvents:UIControlEventTouchUpInside];

[loadImageButton setTitle:@"Present Image" forState:UIControlStateNormal];

[self.view addSubview:loadImageButton];

//Setup the UIImageView

self.myImageView = [[UIImageView alloc] init];

self.myImageView.frame = CGRectMake(0, 0, 320, 407);

self.myImageView.contentMode = UIViewContentModeScaleAspectFit;

[self.view addSubview:self.myImageView];

}

- (void)presentImage{

if(regularLogo){

NSString *key = @"regular-logo";

NSPurgeableData *data = [cache objectForKey:key];

if(!data){

NSString *bundlePath = [[NSBundle mainBundle] bundlePath];

NSString *imagePath = [NSString stringWithFormat: @"%@/MobileAppMastery-Log.png", bundlePath];

data = [NSPurgeableData dataWithContentsOfFile:imagePath];

[cache setObject:data forKey:key];

NSLog(@"Retrieved resource(%@) and added to cache", key);

} else

NSLog(@"Just retrieved resource(%@)", key);;

self.myImageView.image = [UIImage imageWithData:data];

regularLogo = NO;

} else{

NSString *key = @"greyscale-logo";

NSPurgeableData *data = [cache objectForKey:key];

if(!data){

NSString *bundlePath = [[NSBundle mainBundle] bundlePath];

NSString *imagePath = [NSString stringWithFormat:@"%@/MAM_Logo_Square_No_Words_Grayscale.png", bundlePath];

data = [NSPurgeableData dataWithContentsOfFile:imagePath];

[cache setObject:data forKey:key];

NSLog(@"Retrieved resource(%@) and added to cache", key);

} else

NSLog(@"Just retrieved resource(%@)", key);

self.myImageView.image = [UIImage imageWithData:data];

regularLogo = YES;

}

} @end

ObjectiveC 文件操作二的更多相关文章

  1. Node.js文件操作二

    前面的博客 Node.js文件操作一中主要是对文件的读写操作,其实还有文件这块还有一些其他操作. 一.验证文件path是否正确(系统是如下定义的) fs.exists = function(path, ...

  2. 【Directory】文件操作(初识文件操作二)

    上篇我们说了关于文件的创建删除更改可以通过File这个类来完成.对于目录的操作其实File类也可以完成创建删除等相关的操作.用法跟文件的方法大致相同. 那么下面就一起来看一下关于目录相关的用法. 一, ...

  3. 基于VC的声音文件操作(二)

    (二)VC的声音操作 操作声音文件,也就是将WAVE文件打开获取其中的声音数据,根据所需要的声音数据处理算法,进行相应的数学运算,然后将结果重新存储与WAVE格式的文件中去:可以使用CFILE类来实现 ...

  4. DAY8 文件操作(二)

    一.写 1.1写文件 # w:没有文件新建文件,有文件就清空文件 w = open('1.txt', 'w', encoding='utf-8') w.write('000\n') # 在写入大量数据 ...

  5. Java文件操作二:File文件的方法

    一.文件的判断方法 判断方法 .boolean canExecute()判断文件是否可执行 .boolean canRead()判断文件是否可读 .boolean canWrite() 判断文件是否可 ...

  6. ObjectiveC 文件操作一

    1,引用和使用文件 NSFileManager 是一个单例对象,在mac应用中可以获取任何地址,在IOS中获取的是相对应的应用程序的地址.可以使用 defaultManager 来得到当前应用程序地址 ...

  7. AIR文件操作(二):使用文件对象操作文件和目录

    转载于:http://www.flashj.cn/wp/air-file-operation2.html 文件对象是啥?文件对象(File对象)是在文件系统中指向文件或目录的指针.由于安全原因,只在A ...

  8. Python 文件操作二

    readlines就像read没有参数时一样,readlines可以按照行的方式把整个文件中的内容进行一次性读取,并且返回的是一个列表,其中每一行的数据为一个元素 #coding=utf-8 f = ...

  9. C/C++(文件操作二)

    二进制读写才是本质 二进制的读写对文件标记不敏感. eg: 对图片进行加密与解密: 用命令的形式去执行: //xx.exe -c src dest 加密 //xx.exe -d src dest 解密 ...

随机推荐

  1. linux下不重启加硬盘

    linux下热加载磁盘 临时给虚拟机加了一块硬盘,增加后懒得重启,于是看了看热加载 [root@centos5 ~]# cat /proc/scsi/scsi Attached devices: Ho ...

  2. c++多线程同步使用的对象

    线程的同步 Critical section(临界区)用来实现“排他性占有”.适用范围是单一进程的各线程之间.它是: ·         一个局部性对象,不是一个核心对象. ·         快速而 ...

  3. C语言处理CSV文件的方法(一)

    什么是CSV文件 CSV是 Comma-separated values (逗号分隔值)的首字母缩写,它通常是以逗号且不仅限于逗号分隔各个值,我们都叫他CSV. 看下面的例子: China, Shan ...

  4. Vim配置 终端背景色配置

    在终端下使用vim进行编辑时,默认情况下,编辑的界面上是没有显示行号.语法高亮度显示.智能缩进 等功能的.为了更好的在vim下进行工作,需要手动设置一个配置文件:.vimrc.在启动vim时,当前用户 ...

  5. Android 通过HTTP POST请求互联网数据

    @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); s ...

  6. UIWebViewでローカルにあるHTMLを表示する&iOS6からtextAlignmentで指定する値が変更になった

    [objective-c]UIWebViewでローカルにあるHTMLを表示する xcode内にHTMLを格納して.そのHTMLをWebViewで表示する方法です. // UIWebViewの初期化UI ...

  7. mini-httpd源码分析-port.h

    针对不同系统的宏定义,对于Linux而言 /* port.h - portability defines */ #elif defined(linux) # define OS_Linux # def ...

  8. 诞生于饭桌上的jcSQL语言

    相信每个Coder都有心在自己求学阶段可以写一门自己的语言,无论是毕业设计,还是课余爱好:不管是为了提升B格,还是想练手,抑或对其他语言不满,想自己撸一个,只要坚持下去了,都是不错的理由. 现在正值暑 ...

  9. 3.21 采购订单导入MDS

    3.21.1   业务方案描述 同一企业集团内部的不同法人之间,双方间内部往来业务频繁.受集团财务各自独立核算的要求,买方和卖方间采用买卖方式进行业务运作和财务结算. 对于买方,按照内部商定的协议价格 ...

  10. STL中用erase()方法遍历删除元素

    STL中的容器按存储方式分为两类,一类是按以数组形式存储的容器(如:vector .deque):另一类是以不连续的节点形式存储的容器(如:list.set.map).在使用erase方法来删除元素时 ...