我是新手并且首先尝试解压缩文件,我想解压缩我的数据库包含文件并从中复制数据库为此我尝试像
在我的DBManager.m
文件中,我写作
@interface DBManager()
@property (nonatomic, strong) NSString *documentsDirectory;
@property (nonatomic, strong) NSString *databaseFilename;
@property (nonatomic, strong) NSMutableArray *arrResults;
@end
-(instancetype)initWithDatabaseFilename:(NSString *)dbFilename{
self = [super init];
if (self)
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
self.documentsDirectory = [paths objectAtIndex:0];
self.databaseFilename = dbFilename;
[self copyDatabaseIntoDocumentsDirectory];
}
return self;
}
对于解压缩文件,我写的就是,
#pragma mark - Private method implementation
-(void)copyDatabaseIntoDocumentsDirectory
{
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *zipFilePath = [documentsDirectory stringByAppendingPathComponent:@"sampledb.zip"];
NSString *output = [documentsDirectory stringByAppendingPathComponent:self.documentsDirectory];
ZipArchive* za = [[ZipArchive alloc] init];
if( [za UnzipOpenFile:zipFilePath] )
{
if( [za UnzipFileTo:output overWrite:YES] != NO )
{
NSLog(@"Archive unzip success");
}
[za UnzipCloseFile];
}
NSString *destinationPath = [self.documentsDirectory stringByAppendingPathComponent:self.databaseFilename];
if (![[NSFileManager defaultManager] fileExistsAtPath:destinationPath])
{
NSString *sourcePath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:self.databaseFilename];
NSError *error;
[[NSFileManager defaultManager] copyItemAtPath:sourcePath toPath:destinationPath error:&error];
if (error != nil) {
NSLog(@"%@", [error localizedDescription]);
}
}
}
在我的ViewController
类ViewDidLoad
中,我为复制数据库编写代码,如
- (void)viewDidLoad
{
[super viewDidLoad];
self.dbManager = [[DBManager alloc] initWithDatabaseFilename:@"sampledb.sql"];
}
但是我的数据库没有从zip文件复制请给我解决方案。
这里sampledb.zip
是我的zip文件,sampledb.sql
是我的zip文件中的数据库文件。我使用github中的ZipArchive
来解压缩文件。
答案 0 :(得分:1)
至少
NSString *output = [documentsDirectory stringByAppendingPathComponent:self.documentsDirectory];
应该是
NSString *output = [documentsDirectory stringByAppendingPathComponent:@"sampledb.sql"];
如果sql zip文件的来源是捆绑包,则不需要压缩数据库文件,因为Xcode会在将其添加到捆绑包时将其压缩。