ObjectiveC 文件操作二

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 文件操作二

时间: 2024-10-12 16:33:09

ObjectiveC 文件操作二的相关文章

IOS学习之IOS沙盒(sandbox)机制和文件操作(二)

我们看看如何获取应用程序沙盒目录.包括真机的沙盒的目录. 1.获取程序的Home目录 NSString *homeDirectory = NSHomeDirectory(); NSLog(@"path:%@", homeDirectory); 打印结果: 2012-06-17 14:00:06.098 IosSandbox[3536:f803] /Users/rongfzh/Library/Application Support/iPhone Simulator/5.1/ Applic

20141227文件夹和文件操作二

文件操作 对文件里面的内容进行读写 PHP5文件操作 将文件的内容整个进行读取和写入 读取文件 file_get_contents:从一个指定的文件内读取数据内容. 写入内容 file_put_contents:将指定的字符串写入到对应的文件 注意:file_put_contents如果要写入的文件不存在,系统会自动创建,有的话就直接写入 默认的file_put_contents写入数据的时候,会先清空数据再写入 如果要在文件后面追加内容:应该使用file_put_contents的第三个参数

Python第四天(基本文件操作二)

Python基本文件操作 创建一个文件 >>> wu = open('20150118.py','w') >>> wu.write('hello\n') >>> wu.write('world\n') >>> wu.close() 读取一个文件 >>> ang = open('20150118.py') >>> wuang = ang.read() >>> wuang 'hello

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

一.文件的判断方法 判断方法 1.boolean canExecute()判断文件是否可执行 2.boolean canRead()判断文件是否可读 3.boolean canWrite() 判断文件是否可写 4.boolean exists() 判断文件是否存在 5.boolean isDirectory() 6.boolean isFile() 7.boolean isHidden() 8.boolean isAbsolute()判断是否是绝对路径 文件不存在也能判断 二.文件的各种获取属性

【非凡程序员】 OC第十七节课 文件操作二 (归档和解档)

//-----------------------------归档和解档-----(重点)-------.-----------//        //可变的文件流        NSMutableData *nutabdata=[[NSMutableData alloc]init];        //把用归档格式的数据值给可变的文件流        NSKeyedArchiver *keyde=[[NSKeyedArchiver alloc]initForWritingWithMutable

Python学习之文件操作(二)

CSV文件处理 在Python中处理CSV文件可以使用模块csv.有关csv模块的官方资料看这里. 1 读取csv文件 csv.reader(csvfile, dialect='excel', **fmtparams) 使用reader()函数来读取csv文件,返回一个reader对象.reader对象可以使用迭代获取其中的每一行. >>> import csv >>> with open('userlist.csv','rt') as csv_file: csv_co

Java本地文件操作(二)文件夹的创建、删除、重命名

package com.yeqc.testDomo; import java.io.File; public class HelloFolder { public static void main(String[] args) { File folder = new File("my new folder"); folder.mkdir(); System.out.println("文件夹创建完成"); } } package com.yeqc.testDomo;

文件查找记录类型 - TSearchRec - 文件操作(二)

SysUtils单元下的TSearchRec是一个记录类型,主要通过FindFirst, FindNext, and FindClose使用. 接上一篇举例说明TSearchRec常用成员 //sysGetFileList(List,'c:\','*.doc,*.exe'); List通过查找添加多文件 //sysGetFileList(List,'c:\','*.doc'); List通过查找添加单文件 procedure sysGetFileList(List: TStrings; Sour

Objective-C文件操作之NSCoding协议之小练习

如果类遵循了NSCoding协议,则在类中必须实现该协议的编码和解码这两种实例方法.此功能提供了基础的归档和解档功能. 小练习: 1.定义一个Computer类 实例变量:float width;NSString *name; 方法:一个带两个参数的初始化函数: print()函数 dealloc函数 2.定义一个Person类 实例变量:NSString *name;Computer *c;int age; 方法:一个带三个参数的初始化函数: print()函数 dealloc()函数 要求: