如何在Objective-c中保存应用程序的资源文件夹中的文件

时间:2011-11-14 14:19:09

标签: iphone objective-c image

我正在开发一个针对iphone的objective-c应用程序。我的问题是我的应用程序必须保存从网址中获取的图像。该文件夹是只读的我认为..这是我保存图像的代码:

-(void)banner:(NSString *)path{
    NSData * imageData = [[NSData alloc] initWithContentsOfURL: [NSURL URLWithString: path]];
    UIImage *image = [UIImage imageWithData: imageData];
    NSString* resourcePath = [[NSBundle mainBundle] resourcePath];
    NSString* pathEnd =  [resourcePath stringByAppendingFormat:@"/banner.png"];
    NSData *data1 = [NSData dataWithData:UIImagePNGRepresentation(image)];
    NSError *writeError = nil;
    [data1 writeToFile:pathEnd options:NSDataWritingAtomic error:&writeError];
}

但是当我检索图像时,它不在该文件夹中。我该怎么办?

1 个答案:

答案 0 :(得分:9)

你不能,应用程序包是只读的。您应该将任何数据保存在文档或缓存目录中。

-(void)banner:(NSString *)path{
    NSData * imageData = [[NSData alloc] initWithContentsOfURL: [NSURL URLWithString: path]];
    UIImage *image = [UIImage imageWithData: imageData];

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES); 
    NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"banner.png"];

    NSData *data1 = [NSData dataWithData:UIImagePNGRepresentation(image)];
    NSError *writeError = nil;

   [data1 writeToFile:filePath options:NSDataWritingAtomic error:&writeError];

   if (writeError) {
      NSLog(@"Error writing file: %@", writeError);
   }
}

是否有理由首先将数据转换为数据并再次转换回NSData对象?

如果没有,你可以这样做:

-(void)banner:(NSString *)path{
   NSData * imageData = [[NSData alloc] initWithContentsOfURL: [NSURL URLWithString: path]];
   NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);         NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"banner.png"];       
   NSError *writeError = nil;
   [imageData writeToFile:filePath options:NSDataWritingAtomic error:&writeError];

   if (writeError) {
      NSLog(@"Error writing file: %@", writeError);
   }
}