如何将项目写入目录并调用它们,目标c

时间:2012-08-16 06:33:16

标签: objective-c xcode nsurl nsfilemanager directory

您好我从网上下载了一堆照片,我想将它们存储在一个目录中,所以我没有重新加载已下载的照片,我无法理解如何准确地执行此操作并存储照片和从目录等重新加载它们。这就是我到目前为止所拥有的。有人可以解释所涉及的步骤以及如何做到这一点?谢谢

-(void) savePhotoInCache: (NSData*) photoToSave{
   //I dont know if u need bundle ID?
   // NSString * bundleID = [[NSBundle mainBundle] bundleIdentifier];
NSFileManager *fm = [[NSFileManager alloc] init];
NSArray * directoryPaths = [fm URLsForDirectory:NSCachesDirectory inDomains:NSUserDomainMask];
NSLog(@"%@", directoryPaths);
NSURL* dirPath = nil;    
 //Does this create a file in my cache Directory to store my photos?
dirPath = [[directoryPaths objectAtIndex:0] URLByAppendingPathComponent:[NSString stringWithFormat:@"photos.jpg"]];
NSError* theError = nil;
[fm createDirectoryAtURL:dirPath withIntermediateDirectories:YES attributes:nil error:&theError];
// Saves the photo to the file?
[photoToSave writeToURL: dirPath atomically:NO];

NSLog(@"%@", dirPath);
//I get a deprecated warning, new version needs encoding, but I did not specify encoding in writeToURL so what do I use?
NSString * contents = [NSString stringWithContentsOfURL:dirPath ];

//After this how to I access my files and check what the contents of the file are? also, how do I limit the amount of information it stores? thanks

}

2 个答案:

答案 0 :(得分:0)

您不需要自己处理所有事情。我宁愿使用EGO Image Loader来为你做一切。它将(缓存)图像保存在应用程序包目录中,并在需要时重用它们。就研究类而言,它使用图像URL作为主键(从缓存中检索图像)。 它非常快且异步。

只需将其添加到您的项目中并像这样调用它:(这是ARC,所以我不使用-release)

UIImageView *imageView = [[EGOImageView alloc] initWithPlaceholderImage:[UIImage imageNamed:@"placeholder.png"]];
imageView.frame = CGRectMake(0.0f, 44.0f, 320.0f,54.0f);
imageView.imageURL = [NSURL URLWithString:@"www.example.com/1.jpg"] ;
[self.view addSubview:imageView];

我希望它有用。

答案 1 :(得分:0)

检查如何获取这样的保存内容:

NSArray *dirContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:dirPath error:nil];

现在过滤器包含如下:

NSPredicate *fltr = [NSPredicate predicateWithFormat:@"self ENDSWITH '.jpg'"];
NSPredicate *fltr1 = [NSPredicate predicateWithFormat:@"self ENDSWITH '.png'"];
NSArray *onlyJPGs = [dirContents filteredArrayUsingPredicate:fltr];
NSArray *onlyPNGs = [dirContents filteredArrayUsingPredicate:fltr1];

获取所有图片内容

for(NSString *fileName in dirContents)
{
    NSString *imgPath = [dirPath stringByAppendingFormat:fileName];
    UIImage *img = [UIImage imageWithContentsOfFile:imgPath];
    //You have image use it where u want
}

如果您有许多图像,请使用延迟加载图像