2009-04-26 4 views
2

내 appDelegate 클래스에서 SQLite 데이터베이스를 열고 데이터베이스가 필요한 다른 모든 클래스에서 해당 데이터베이스를 참조하려고합니다. 나는 시도했다 : static sqlite3 * database = nil;iphone 전역 변수

그러나 appDelegate.database를 사용하여 다른 클래스에서 참조하려고하면 "오류 : 멤버 '데이터베이스'에 대한 구조체 또는 공용체가 아닌 요청이 컴파일됩니다." 당신은 이러한 유형의 성질을 어떻게 참고합니까?

답변

6

당신은 따라 일반 식을 통해 응용 프로그램의 위임에 저장된 변수에 액세스해야합니다

YourAppDelegateName *delegate = (YourAppDelegateName *)[[UIApplication sharedApplication]delegate]; 
//access specific variables in delegate as follows: 
sqlite3 *temp = delegate.database; 
1

난 당신이 sqlite가에 대한 FMDB 목표 C 래퍼를 사용하는 것이 좋습니다. 그것은 정말 sqlite 데이터베이스에 대한 액세스를 단순화합니다. 당신은

당신이 액세스 앱 대리자를 사용 (다음 예제 코드를 사용하고 다른 클래스에서 DB를 액세스 할 수있는 NSString * DB_PATH 변수를 사용할 수

그런 http://code.google.com/p/flycode/source/browse/trunk/fmdb#fmdb/src

에서 다운로드 할 수 있습니다 DB_PATH, 다음 DB를 액세서하는

FMDatabase *db = [FMDatabase databaseWithPath:db_path]; 

를 사용합니다. 아래의 샘플 코드를 참조하십시오.

- (NSString *) initialize_db { 
    NSString *DATABASE_RESOURCE_NAME = @"yourDbName"; 
    NSString *DATABASE_RESOURCE_TYPE = @"db"; 
    NSString *DATABASE_FILE_NAME = @"yourDbName.db"; 

    // copy the database from the bundle if necessary 
    // look to see if DB is in known location (~/Documents/$DATABASE_FILE_NAME) 
    NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString *documentFolderPath = [searchPaths objectAtIndex: 0]; 
    NSString *dbFilePath = [documentFolderPath stringByAppendingPathComponent: DATABASE_FILE_NAME]; 
    [dbFilePath retain]; 

    if (! [[NSFileManager defaultManager] fileExistsAtPath: dbFilePath]) { 
     // didn't find db, need to copy 
     NSString *backupDbPath = [[NSBundle mainBundle] 
            pathForResource:DATABASE_RESOURCE_NAME 
            ofType:DATABASE_RESOURCE_TYPE]; 
     if (backupDbPath == nil) { 
      // couldn't find backup db to copy, bail 
      NSLog (@"couldn't init db"); 
      return NULL; 
     } else { 
      BOOL copiedBackupDb = [[NSFileManager defaultManager] 
            copyItemAtPath:backupDbPath 
            toPath:dbFilePath 
            error:nil]; 
      if (! copiedBackupDb) { 
       // copying backup db failed, bail 
       NSLog (@"couldn't init db"); 
       return NULL; 
      } 
     } 
    } 


    return dbFilePath; 

} 

- (void)applicationDidFinishLaunching:(UIApplication *)application { 

    FMResultSet *item_rs; 


    // copy the database from the bundle if necessary 
    db_path = [self initialize_db]; 
    if (! db_path) { 
     // TODO: alert the user! 
     NSLog (@"couldn't init db"); 
     return; 
    } 


    FMDatabase *db = [FMDatabase databaseWithPath:db_path]; 
    if (![db open]) { 
     NSLog(@"Could not open the db"); 
    } 


    FMResultSet *rs = [db executeQuery:@"select * from yourTable"]; 
    if ([db hadError]) { 
     NSLog(@"Err %d: %@", [db lastErrorCode], [db lastErrorMessage]); 
    } 

    while ([rs next]) { 
     [yourArray addObject:[rs stringForColumn:@"yourColumnName"]]; 

    } 

    [rs close]; 



    [db close]; 


    // Configure and show the window 
    [window addSubview:[navigationController view]]; 
    [window makeKeyAndVisible]; 
} 
1

데이터베이스의 인스턴스 속성을 만들어야했습니다. 정적 선언이 충분했다는 나의 가정은 부정확했다. BTW, FMDB/ORM 조언은 훌륭합니다. 나는 ORM의 열렬한 팬이다. 그러나,이 프로젝트는 내 첫 번째 아이폰이며 그것은 데이터베이스 작업의 작은 금액이며 내가 배우고 싶습니다. 그래서, 나는 그것을 오래된 학교에서 할 것입니다. 조언 해주셔서 감사합니다. 여기

는 희망이 도움이 .. 내 글로벌 참조 작동하도록 만든 코드 변경이있는 사람 :

/* myAppDelegate.h file */ 
#import <sqlite3.h> 

@interface myAppDelegate : NSObject <UIApplicationDelegate> { 
... // you may have windows etc here 
    sqlite3 *database; 

} 

@property (readwrite) sqlite3 *database; 


/* myAppDelegate.m file */ 
@implementation myAppDelegate 
... 
@synthesize database; 

/* some method in some class that uses the database */ 
- (void) getSomeData 
{ 
    myAppDelegate *appDelegate = (myAppDelegate *) [[ UIApplication sharedApplication ] delegate ]; 

    const char *sql = "SELECT * FROM myTable"; 
     sqlite3_stmt *selectstmt; 
     if(sqlite3_prepare_v2(appDelegate.database, sql, -1, &selectstmt, NULL) == SQLITE_OK) 
{ 
// get the data here. 
} 

}