2009-04-26 7 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のObjective 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

データベースのインスタンスプロパティを作成する必要がありました。静的宣言が十分だったという私の前提は正しくありませんでした。ところで、FMDB/ORMのアドバイスは素晴らしいです。私はORMの巨大なファンです。しかし、このプロジェクトは私の最初のiphoneであり、それはデータベース作業の少量であり、私は学びたいと思っています。だから、私は古い学校でやるつもりです。アドバイスをいただきありがとうございます。

/* 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. 
} 

} 
:ここ

は、それが誰かの役に立てば幸い..私は私のグローバル参照の仕事をするために作られたコードの変更です