iPhone: не удается найти ресурс - PullRequest
0 голосов
/ 03 августа 2009

В моем приложении я хочу скопировать файл из моего пакета в каталог документов, чтобы изменить его.

Вот мой код:

+(BOOL) copyDB: (NSString*) pdbName {
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSError *error;
    NSString *dbPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES) objectAtIndex: 0];
    dbPath = [dbPath stringByAppendingPathComponent: @"myApp"];
    dbPath = [dbPath stringByAppendingPathComponent: @"Profiles"];
    dbPath = [dbPath stringByAppendingPathComponent: @"ES-EN"];

    dbPath = [dbPath stringByAppendingPathExtension: @"prof"];

    if([fileManager fileExistsAtPath: dbPath]) {
        DebugLog(@"file exists at path %@", dbPath);
        return FALSE;
    }

    NSString *defaultDBPath = [ [ [NSBundle mainBundle] resourcePath] stringByAppendingPathComponent: @"ES-EN"];
    defaultDBPath = [defaultDBPath stringByAppendingPathExtension: @"prof"];

    DebugLog(@"dbPath: %@", dbPath);
    DebugLog(@"defaultDBPath: %@", defaultDBPath);

    if(![fileManager fileExistsAtPath: defaultDBPath]) {
        DebugLog(@"Cannot find resource file");
        return FALSE;
    }

    BOOL success = [fileManager copyItemAtPath: defaultDBPath toPath: dbPath error: &error];

    if (!success) {
        DebugLog(@"!success: Failed to create writable database file with message '%@'.", [error localizedDescription]);
        UIAlertView *msg = [[UIAlertView alloc]
                            initWithTitle:@"Error"
                            message: [NSString stringWithFormat: @"Failed to create writable database file with message '%@'.", [error localizedDescription] ]
                            delegate:self cancelButtonTitle:@"OK"
                            otherButtonTitles:nil, nil];
        [msg show];
        [msg release];
        return FALSE;
    }

    [ [UserProfile sharedUserProfile] writeInitialData: pdbName];

    //Creating fruits folder
    NSString *dicDir = [Fruits_Dir stringByAppendingPathComponent: pdbName];

    //Does a directory exist?
    if ( ![fileManager fileExistsAtPath: dicDir] )
    {
        //Create a directory
        DebugLog(@"Creating userName dir");
        if (![fileManager createDirectoryAtPath: dicDir attributes:nil])
        {
            DebugLog(@"failed to create dicDir");
        }
    }
    return TRUE;
}

Полагаю, этот код должен работать. Каким-то образом он работает как на симуляторе, но не работает на устройстве. Я получаю журнал, что файл ресурса не может быть найден.

В чем может быть проблема?

Спасибо.

1 Ответ

1 голос
/ 03 августа 2009

Это может произойти, если файл ресурса был случайно удален как ссылка из вашего проекта XCode.

Если файл когда-то был там, то, скорее всего, он был установлен в каталог приложения симулятора. Даже после удаления его из XCode файл останется там, и ваше приложение будет работать в симуляторе.

Но как только вы установите его на устройство, файл будет отсутствовать.

Убедитесь, что файл указан в ресурсах вашего проекта XCode, и полностью удалите приложение из симулятора и попробуйте его снова, чтобы синхронизировать все.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...