iphone全局变量

时间:2009-04-26 13:24:10

标签: iphone objective-c

我想在appDelegate类中打开我的SQLite数据库,并在我需要数据库的所有其他类中引用该数据库。我尝试过使用: static sqlite3 * database = nil;

但是当我尝试在appDelegate.database的其他类中引用它时,我得到一个编译错误“错误:请求成员'数据库',而不是结构或联合。”你如何引用这些类型的专业?

3 个答案:

答案 0 :(得分:6)

您应该通过以下通用公式访问存储在app Delegate中的任何变量:

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

答案 1 :(得分:1)

我建议您使用FMDB Objective C包装器进行sqlite。它将真正简化对sqlite数据库的访问。您可以从

下载

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

然后,

您可以使用以下示例代码,并使用NSString * db_path变量从其他类访问您的数据库(您使用您的app委托访问db_path,然后使用

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];
}

答案 2 :(得分: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.
}

}
相关问题