在iphone中全局定义sqlite3数据库

在iphone中全局定义sqlite3数据库,iphone,objective-c,sqlite,Iphone,Objective C,Sqlite,是否有一种方法可以全局定义sqlite3数据库。我已经搜索了很多地方,但大多数地方都使用单例或外部方法来定义全局变量。我两样都试过了,但都没有成功。 实际上,我正在尝试在许多文件上使用sqlite3*数据库来创建、插入或选择。我真的需要知道在哪里以及如何创建全局变量。 我正在appDelegate中定义sqlite3数据库,并检查数据库的打开或关闭连接。如何将sqlite3*数据库从appdelegate调用到其他ViewController或NSObject /// AppDelegat

是否有一种方法可以全局定义sqlite3数据库。我已经搜索了很多地方,但大多数地方都使用单例或外部方法来定义全局变量。我两样都试过了,但都没有成功。 实际上,我正在尝试在许多文件上使用sqlite3*数据库来创建、插入或选择。我真的需要知道在哪里以及如何创建全局变量。 我正在appDelegate中定义sqlite3数据库,并检查数据库的打开或关闭连接。如何将sqlite3*数据库从appdelegate调用到其他ViewController或NSObject

   /// AppDelegate.h
   @interface AppDelegate : NSObject <UIApplicationDelegate> {
       sqlite3 *database;
       AppDelegate *delegate;
   }

    /// AppDelegate.m

      -(void)checkAndCreateDatabase_2{

        NSString *databaseName = @"main.sqlite";
        NSArray *documentPaths =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentsDir = [documentPaths objectAtIndex:0];
        databasePath = [documentsDir stringByAppendingPathComponent:databaseName];

       }
///AppDelegate.h
@接口AppDelegate:NSObject{
sqlite3*数据库;
AppDelegate*代表;
}
///AppDelegate.m
-(无效)checkAndCreateDatabase_2{
NSString*databaseName=@“main.sqlite”;
NSArray*DocumentPath=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,是);
NSString*documentsDir=[documentPaths objectAtIndex:0];
databasePath=[documentsDir stringByAppendingPathComponent:databaseName];
}

将属性添加到AppDelegate.h

@property (nonatomic,readonly) sqlite3 *database;
在AppDelegate.m中合成

@synthesize database;
并通过以下代码在ViewControllers/nsobjects中使用它:

sqlite3 *database = [(AppDelegate*)[UIApplication sharedApplication].delegate database];
@接口AppDelegate:NSObject{
sqlite3*数据库;
//AppDelegate*delegate;//无需声明此项,因此请删除此项。
}
@属性(非原子,保留)sqlite3*数据库;
@综合数据库//外接程序AppDelegate.m
//在AnyViewController.m中,访问AppDelegate,如下所示。
-(无效)viewDidLoad
{
AppDelegate*AppDelegate=[[UIApplication sharedApplication]委托];
sqlite3*数据库=[appDelegate数据库];//对DB执行任何操作
}

希望有帮助。

您最好为sqlite db的创建实现一个单独的类,并为其函数创建一个类级方法来实例化该类的对象,并在其他控制器中使用该对象来访问或修改数据库

给出了一个错误。在非结构或联合中请求成员“委托”。奇怪。。。试试这个:sqlite3*数据库=[(AppDelegate*)[[UIApplication sharedApplication]委托]数据库];对不起,兄弟。但这次它给出了警告:“AppDelegate”可能不会响应“-delegate”。然后还会抛出“未识别的选择器发送到实例”。我想这是另一种方式。你以前试过吗?检查你的Tab_Table_WinAppDelegate类如果它包含appDelegate属性/方法,我想它与问题无关。。。
@interface AppDelegate : NSObject <UIApplicationDelegate> {
   sqlite3 *database;
   //AppDelegate *delegate; // No need to declare this so remove this.
}
@property (nonatomic,retain) sqlite3 *database;

@synthesize database; //Add in AppDelegate.m

//In AnyViewController.m access AppDelegate as follow.
 -(void)viewDidLoad
 {
      AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
      sqlite3 *database = [appDelegate database]; //Do whatever you want to do with DB
 }