Bea*_*ker 6 iphone objective-c
我想将一组图像保存到文档文件夹.我设法将图像保存为NSData并使用下面的方法检索它,但保存数组似乎超出了我.我看了几个其他相关的问题,似乎我做的一切都是正确的.
将图像添加为NSData并保存图像:
[imgsData addObject:UIImageJPEGRepresentation(img, 1.0)];
[imgsData writeToFile:dataFilePath atomically:YES];
Run Code Online (Sandbox Code Playgroud)
检索数据:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:@"imgs.dat"];
[self setDataFilePath:path];
NSFileManager *fileManager = [NSFileManager defaultManager];
if([fileManager fileExistsAtPath:dataFilePath])
imgsData = [[NSMutableArray alloc] initWithContentsOfFile:dataFilePath];
Run Code Online (Sandbox Code Playgroud)
因此,使用上述工作将图像写为NSData,而不是作为NSData的图像数组.它在数组中,但它有0个对象,这是不正确的,因为我保存的数组有几个.有没有人有任何想法?
首先,你应该刷新Cocoa Memory Management,第一行代码有点担心.
对于数据序列化,您可能想要使用NSPropertyListSerialization.此类序列化数组,字典,字符串,日期,数字和数据对象.与initWithContentsOfFile:方法不同,它有一个错误报告系统.方法名称和参数有点长,以适应一行,所以有时您可能会看到它们用东方波兰圣诞树表示法编写.要保存imgsData对象,您可以使用:
NSString *errString;
NSData *serialized =
[NSPropertyListSerialization dataFromPropertyList:imgsData
format:NSPropertyListBinaryFormat_v1_0
errorDescription:&errString];
[serialized writeToFile:dataFilePath atomically:YES];
if (errString)
{
NSLog(@"%@" errString);
[errString release]; // exception to the rules
}
Run Code Online (Sandbox Code Playgroud)
要重新阅读,请使用
NSString *errString;
NSData *serialized = [NSData dataWithContentsOfFile:dataFilePath];
// we provide NULL for format because we really don't care what format it is.
// or, if you do, provide the address of an NSPropertyListFormat type.
imgsData =
[NSPropertyListSerialization propertyListFromData:serialized
mutabilityOption:NSPropertyListMutableContainers
format:NULL
errorDescription:&errString];
if (errString)
{
NSLog(@"%@" errString);
[errString release]; // exception to the rules
}
Run Code Online (Sandbox Code Playgroud)
检查内容errString以确定出了什么问题.请记住,这两种方法都被弃用而不赞成使用dataWithPropertyList:format:options:error:和propertyListWithData:options:format:error:方法,但这些方法是在Mac OS X 10.6中添加的(我不确定它们是否可在iOS上使用).
| 归档时间: |
|
| 查看次数: |
7256 次 |
| 最近记录: |