1

私はiOSアプリ開発にまったく慣れていません。

レコードをDBに保存してそこからフェッチするサンプルDBアプリを構築しようとしています。

シミュレーターでテストすると、アプリはうまく機能します。ローカル データベースを作成し、必要に応じてプログラムでコピーを作成しています。また、「バンドル リソースのコピー」でローカル DB が参照されていることも確認しました。

しかし、私が得ているエラーは、「* キャッチされていない例外 'NSInvalidArgumentException' が原因でアプリを終了しています。理由: '* -[NSFileManager copyItemAtPath:toPath:error:]: source path is nil' '」です。

この問題の原因となっているコードは " [FileManager copyItemAtPath:databasePathFromApp toPath:DBPath error:nil]; " だと思います。

シミュレーターでは完全に機能しますが、デバイスでテストする場合は機能しません。

助けを期待しています。

私のコードは、

- (id)init {

    self = [super init];

    //Datbase Name
    DBName=@"Person.sqlite3";

    //Getting DB Path
    NSArray *documentsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

    NSString *documentsDir = [documentsPath objectAtIndex:0];

    DBPath=[documentsDir stringByAppendingPathComponent:DBName ];
    //DBPath = [[NSString alloc] initWithString: [documentsDir stringByAppendingPathComponent:DBName]];
    NSLog(@"DBPath is  %@",DBPath);

    return self;

}


-(void)checkAndCreateDB{

    BOOL Success;

    //NSFileManager maintains File
    NSFileManager *FileManager = [NSFileManager defaultManager];
    NSLog(@"line 1");

    //Checks Database Path
    Success = [FileManager fileExistsAtPath:DBPath];
    NSLog(@"line 2");

    //If file exists, it returns true
    if(Success)return;
    NSLog(@"line 3");

    //NSString *databasePathFromApp = [[[NSBundle mainBundle]resourcePath]stringByAppendingPathComponent:DBName];

    // Get the path to the database in the application package
    NSString *databasePathFromApp=[[NSBundle mainBundle] pathForResource:@"Person.sqlite3" ofType:@"sqlite3"];
    NSLog(@"line 4");

    [FileManager copyItemAtPath:databasePathFromApp toPath:DBPath error:nil];
    //[FileManager release];
    NSLog(@"line 5");

}

NSLOG 行 (4 行目) の後のデバイスでのテスト中に、アプリケーションがクラッシュします。しかし、シミュレーターではうまく機能します。

どうもありがとう

4

2 に答える 2

0

この行を変更

NSString *databasePathFromApp=[[NSBundle mainBundle] pathForResource:@"Person.sqlite3" ofType:@"sqlite3"];

NSString *databasePathFromApp=[[NSBundle mainBundle] pathForResource:@"Person" ofType:@"sqlite3"];

また、大文字に注意してください。iOS デバイスでは大文字と小文字が区別されますが、シミュレーターでは大文字と小文字が間違っていても問題ありません。

于 2012-01-16T03:42:20.343 に答える
0

デバイスはアプリ バンドルに書き込めません。Documents ディレクトリを使用する必要があります。

Documents ディレクトリ パスを取得する方法は次のとおりです。

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:fileName];

アプリ バンドルに最初のデータベースがある場合は、最初の起動時にドキュメントにコピーします。

于 2012-01-16T02:51:35.427 に答える