星空5G 导航

ios nsfilemanager打不开是怎么回事-

2024-09-12编辑:本站
Object-c的NSFileManager不能访问相对路径下的文件,怎么处理这个问题?~

ios里,文件路径没有相对路径的概念.

iOS中的数据持久化方式,基本上有以下四种:属性列表、对象归档、SQLite3和Core Data

  1.属性列表
  涉及到的主要类:NSUserDefaults,一般 [NSUserDefaults standardUserDefaults]就够用了
  @interface User : NSObject
  @property (nonatomic, assign) NSInteger userID;
  @property (nonatomic, copy) NSString *name;
  @end
  使用方法
  1).分开存取
  // 存
  [[NSUserDefaults standardUserDefaults] setInteger:userID forKey:@”userID”];
  [[NSUserDefaults standardUserDefaults] setObject:name forKey:@”name”];
  // 取
  NSInteger uId = [[[NSUserDefaults standardUserDefaults] integerValueForKey:@”userID”];
  NSString* name = [[NSUserDefaults standardUserDefaults] stringForKey:@”name”];

  2).按对象存取
  // 存
  [[NSUserDefaults standardUserDefaults] setObject:self forKey:@”user”];
  // 取
  User* u = [[NSUserDefaults standardUserDefaults] objectForKey”@”user”];
  
  2.对象归档
  要使用对象归档,对象必须实现NSCoding协议.大部分Object C对象都符合NSCoding协议,也可以在自定义对象中实现NSCoding协议,要实现NSCoding协议,实现两个方法:
  - (void) encodeWithCoder:(NSCoder *)encoder 与 -(void)initWithCoder:(NSCoder *)encoder
  同时,建议对象也同时实现NSCopying协议,该协议允许复制对象,要实现NSCopying协议须实现 -(id)copyWithZone:(NSZone *)zone 方法 。
  @interface User : NSObject
  @property (nonatomic, assign) NSInteger userID;
  @property (nonatomic, copy) NSString *name;
  @end
  @implementation User
  // 以下两个方法一定要实现,不然在调用的时候会crash
  - (void)encodeWithCoder:(NSCoder *)aCoder;
  {
  // 这里放置需要持久化的属性
  [aCoder encodeObject:[NSNumber numberWithInteger:self.userID] forKey:@”userID”];
  [aCoder encodeObject:self.name forKey:@"name"];
  }
  - (id)initWithCoder:(NSCoder *)aDecoder
  {
  if (self = [self init])
  {
  // 这里务必和encodeWithCoder方法里面的内容一致,不然会读不到数据
  self.userID = [[aDecoder decodeObjectForKey:@"userID"] integerValue];
  self.name = [aDecoder decodeObjectForKey:@"name"];
  }
  return self;
  }
  // 使用方法
  + (BOOL)save {
  NSError *error = nil;
  // 确定存储路径,一般是Document目录下的文件
  NSString* fileName = [self getFileName];
  NSString* filePath = [self getFilePath];
  if (![[NSFileManager defaultManager] createDirectoryAtPath:filePath withIntermediateDirectories:YES attributes:nil error:&error]) {
  NSLog(@”创建用户文件目录失败”);
  return NO;
  }
  return [NSKeyedArchiver archiveRootObject:self toFile:[fileName:userId]];
  }
  @end
  
  3.SQLite3
  SQLite是一个开源的嵌入式关系数据库,它在2000年由D. Richard Hipp发布,它的减少应用程序管理数据的开销,SQLite可移植性好,很容易使用,很小,高效而且可靠。
  SQLite嵌入到使用它的应用程序中,它们共用相同的进程空间,而不是单独的一个进程。从外部看,它并不像一个RDBMS,但在进程内部,它却是完整的,自包含的数据库引擎。 嵌入式数据库的一大好处就是在你的程序内部不需要网络配置,也不需要管理。因为客户端和服务器在同一进程空间运行。SQLite 的数据库权限只依赖于文件系统,没有用户帐户的概念。SQLite 有数据库级锁定,没有网络服务器。它需要的内存,其它开销很小,适合用于嵌入式设备。你需要做的仅仅是把它正确的编译到你的程序。
  关于SQLite的开发资料较多,这里不再细说。只是建议不直接操作SQLite库,而是采用一些开源的第三方库来进行操作。
  对SQLite都做了不错的封装。

  4.Core Data
  Core Data本质上是使用SQLite保存数据,但是它不需要编写任何SQL语句。

  要使用Core Data,需要在Xcode中的数据模型编辑器中设计好各个实体以及定义好他们的属性和关系。之后,通过操作这些对象,结合Core Data完成数据的持久化:

  NSManagedObjectContext *context = [appDelegate managedObjectContext];
  NSError *error;
  NSString *fieldName = [NSString stringWithFormat:@"test%d", i];
  UITextField *theField = [self valueForKey:fieldName];
  NSFetchRequest *request = [[NSFetchRequest alloc] init];
  //创 建描述语句,需求Line对象。类似于在数据库中限定为Line表。
  NSEntityDescription *entityDescription = [NSEntityDescription entityForName:@"Line" inManagedObjectContext:context];
  [request setEntity:entityDescription];
  //创建限制性语句,类似于SQL语句中的 where lineNum = i
  NSPredicate *pred = [NSPredicate predicateWithFormat:@"(lineNum = %d)", i];
  [request setPredicate:pred];
  NSManagedObject *theLine = nil;
  NSArray *objects = [context executeFetchRequest:request error:&error];
  if (objects == nil){
  NSLog(@”There was an error!”);
  // Do whatever error handling is appropriate
  }
  if ([objects count] > 0){ //如果符合条件的object存在,则取出
  theLine = [objects objectAtIndex:0];
  }
  else { //如果不存在,则插入一个新的.
  theLine = [NSEntityDescription insertNewObjectForEntityForName:@"Line"
  inManagedObjectContext:context];
  [theLine setValue:[NSNumber numberWithInt:i] forKey:@”lineNum”]; //设置这个object的属性,coredata会自动将其写入sqlite
  [theLine setValue:theField.text forKey:@"lineText"];
  [request release];
  }
  }

  下面是其取数据的过程:

  Core_Data_PersistenceAppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
  NSManagedObjectContext *context = [appDelegate managedObjectContext];
  NSEntityDescription *entityDescription = [NSEntityDescription entityForName:@"Line"
  inManagedObjectContext:context];
  NSFetchRequest *request = [[NSFetchRequest alloc] init];
  [request setEntity:entityDescription];
  NSError *error;
  NSArray *objects = [context executeFetchRequest:request error:&error];
  if (objects == nil)
  {
  NSLog(@”There was an error!”);
  // Do whatever error handling is appropriate
  }
  //每一个对象在CoreData中都表示为一个NSManagedObject对象(类似于数据库表中的每一行),他的属性通过键/值 方式获取
  for (NSManagedObject *oneObject in objects)
  {
  NSNumber *lineNum = [oneObject valueForKey:@"lineNum"];
  NSString *lineText = [oneObject valueForKey:@"lineText"];
  }
  [request release];

iOS文件管理系统NSFileManager使用详解
1,找到自己的程序的目录: NSHomeDirectory() ,目录结构为:
---Documents/
---"YourAppName.app"
---Library/
---自己创建的文件夹 或 "自己创建的文件"
---tmp/
所以要找到自己程序的Documents文件夹,可以使用[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
也可以使用:
NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *string=[paths objectAtIndex:0];
两者功能应该一样。

2,文件一些主要操作可以通过NSFileManage 来操作,可以通过 [NSFileManger defaultManger] 得到它得实例。

3,使用[aNSString stringByAppendingPathCompnent:aNSString] 来创建文件路径

4,tmp 目录我们可以在里面写入一些程序运行时需要用得数据,里面写入得数据在程序退出后会没有。
可以通过NSTemporaryDirectory();获得其路径。

5,NSFileManager的一些相关操作:
1)创建文件夹:
NSString *myDirectory = [documentDirectory stringByAppendingPathComponent:@"test"];
BOOL ok = [fileManage createDirectoryAtPath:myDirectory withIntermediateDirectories:YES attributes:nil error:&error];
2)取得一个目录下得所有文件名:(如上面的myDirectory)可用
NSArray *file = [fileManager subpathsOfDirectoryAtPath: myDirectory error:nil];

NSArray *files = [fileManager subpathsAtPath: myDirectory ];

NSArray *files=[fileManager contentsOfDirectoryAtPath:documentDirectory error:&error];

3)读取某个文件:
NSData *data = [fileManger contentsAtPath:myFilePath];//myFilePath是包含完整路径的文件名
或直接用NSData 的类方法:
NSData *data = [NSData dataWithContentOfPath:myFilePath];

4)保存某个文件:
可以用 NSFileManager的
- (BOOL)createFileAtPath:(NSString *)path contents:(NSData *)data attributes:(NSDictionary *)attr;
或 NSData 的
- (BOOL)writeToFile:(NSString *)path atomically:(BOOL)useAuxiliaryFile;
- (BOOL)writeToFile:(NSString *)path options:(NSUInteger)writeOptionsMask error:(NSError **)errorPtr;

5)字符串写入文件:
[str writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:&error];
[NSString stringWithContentsOfFile...];

6)移动文件:
if ([fileMgr moveItemAtPath:filePath toPath:filePath2 error:&error] != YES)

7)删除文件:
if ([fileMgr removeItemAtPath:filePath2 error:&error] != YES)

8)判断是否是文件夹:
BOOL isDir = NO;
[fileManager fileExistsAtPath:path isDirectory:(&isDir)];
if (isDir) { ...}

9)以下代码用于获取本机上的文件资源或图片
获取文本:
NSFileManager *fileManager=[NSFileManager defaultManager];
NSData *data=[fileManager contentsAtPath:@"/Developer/Documentation/wxWidgets/docs/lgpl.txt"];
NSString *string=[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"%@",string);
获取图片:
NSData *myData=[fileManager contentsAtPath:@"/Users/ruby/Desktop/Photo1.jpg"];
UIImage *myImage=[UIImage imageWithData:myData];
imageView.image=myImage;

相关内容

首页 新知 身健
返回顶部

© 星空5G w.xkyn.com