gpt4 book ai didi

iphone - 如何在委托(delegate)和 Controller 文件中使用自定义数据库 header 的相同对象?

转载 作者:行者123 更新时间:2023-12-03 19:57:32 26 4
gpt4 key购买 nike

全部我想为这样的数据库创建头文件。它包含以下六个文件。

数据库.h

    #import <Foundation/Foundation.h>
#import "sqlite3.h"
@interface Database : NSObject
{
sqlite3 *mydb;
}

-(void) openDB;
-(NSString *) filePath;
-(BOOL) createTable;
+(Database*)sharedInstance;
@end

数据库.m #导入“数据库.h”

    @implementation Database
static Database* dbase = nil;

+(Database*)sharedInstance
{
if (dbase == nil)
{
dbase = [[Database alloc] init];
}
return dbase;
}

-(NSString *) filePath{
NSArray *paths =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
NSString *documentsDir = [paths objectAtIndex:0];
NSLog(@"DBPATH:%@",documentsDir);
return [documentsDir stringByAppendingPathComponent:@"userdb.sqlite"];

}

-(void) openDB {
if (sqlite3_open([[self filePath]UTF8String],&mydb) != SQLITE_OK) {
sqlite3_close(mydb);
NSAssert(0,@"Database failed to Open ...");
}
BOOL result = [self createTable];
NSLog(@"Table Avi gayu 6...!!! %u",result);

}

- (BOOL) createTable
{
sqlite3_stmt *createStmt;
createStmt = nil;
NSString *tableName = @"user_table";

if ( createStmt == nil )
{
NSString *query = [NSString stringWithFormat:@"create table if not exists %@ \
(userid INTEGER PRIMARY KEY, \
name TEXT NOT NULL)",tableName];
if (sqlite3_prepare_v2(mydb, [query UTF8String], -1, &createStmt, NULL)!= SQLITE_OK )
{
return NO;
}
sqlite3_exec(mydb, [query UTF8String], NULL, NULL, NULL);
return YES;
}
return YES;
}

@end

UIDBDemoAppDelegate.h

  #import <UIKit/UIKit.h>
#import "Database.h"

@class UIDBDemoViewController;

@interface UIDBDemoAppDelegate : NSObject <UIApplicationDelegate> {
UIWindow *window;
UIDBDemoViewController *viewController;

}

@property (nonatomic, retain) IBOutlet UIWindow *window;
@property (nonatomic, retain) IBOutlet UIDBDemoViewController *viewController;

@end

UIDBDemoAppDelegate.m

    #import "UIDBDemoAppDelegate.h"
#import "UIDBDemoViewController.h"

@implementation UIDBDemoAppDelegate

@synthesize window;
@synthesize viewController;



#pragma mark -
#pragma mark Application lifecycle

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
[[Database sharedInstance] openDB];
[self.window addSubview:viewController.view];
[self.window makeKeyAndVisible];

return YES; }

- (void)applicationWillResignActive:(UIApplication *)application { }


- (void)applicationDidEnterBackground:(UIApplication *)application { }


- (void)applicationWillEnterForeground:(UIApplication *)application { }


- (void)applicationDidBecomeActive:(UIApplication *)application { }


- (void)applicationWillTerminate:(UIApplication *)application { }


#pragma mark -
#pragma mark Memory management

- (void)applicationDidReceiveMemoryWarning:(UIApplication *)application { }


- (void)dealloc {
[viewController release];
[window release];
[super dealloc]; }


@end

UIDBDemoViewController.h

#import <UIKit/UIKit.h>
#import "UIDBDemoAppDelegate.h"

@interface UIDBDemoViewController : UIViewController
<UITableViewDataSource> {
UIView *addView;
UILabel *uid,*unm,*cellLbl1,*cellLbl2;
UITextField *txtuid,*txtunm;
UIButton *btnadd,*btnshow;
UITableView *mytabView;
NSMutableArray *uidarray,*unmarray;
}
@property (retain, nonatomic) UIView *addView;
@property (retain, nonatomic) UILabel *uid,*unm; @property (retain, nonatomic) UITextField *txtuid,*txtunm;
@property (retain, nonatomic) UIButton *btnadd,*btnshow;
-(void) addClicked;
-(void) showClicked;
-(void) readData;
-(void) rmkeyboard;
@end

UIDBDemoViewController.m

#import "UIDBDemoViewController.h"


@implementation UIDBDemoViewController
@synthesize addView, uid,unm,txtuid,txtunm,btnadd,btnshow;

- (void)loadView
{


//Add myView
CGRect rect = CGRectMake(0, 0, 320, 480);
addView = [[UIView alloc] initWithFrame:rect];
addView.backgroundColor=[UIColor blackColor];

//Adding two Name and Password Label into myView
uid=[[UILabel alloc] initWithFrame:CGRectMake(20, 100, 100, 35)];
uid.text=@"User ID:";
uid.textAlignment=UITextAlignmentRight;
uid.textColor=[UIColor whiteColor];
uid.backgroundColor=[UIColor blackColor];
[addView addSubview:uid];

unm=[[UILabel alloc] initWithFrame:CGRectMake(20, 140, 100, 35)];
unm.text=@"User Name:";
unm.textAlignment=UITextAlignmentRight;
unm.textColor=[UIColor whiteColor];
unm.backgroundColor=[UIColor blackColor];
[addView addSubview:unm];


//Adding Two Name and Password TextField into myView
txtuid=[[UITextField alloc] initWithFrame:CGRectMake(130, 100, 150, 30)];
txtuid.placeholder=@"Enter User ID";
txtuid.borderStyle=UITextBorderStyleRoundedRect;
[txtuid addTarget:self action:@selector(rmkeyboard) forControlEvents:UIControlEventEditingDidEndOnExit];
[addView addSubview:txtuid];

txtunm=[[UITextField alloc] initWithFrame:CGRectMake(130, 140, 150, 30)];
txtunm.placeholder=@"Enter User Name";
txtunm.borderStyle=UITextBorderStyleRoundedRect;
[txtunm addTarget:self action:@selector(rmkeyboard) forControlEvents:UIControlEventEditingDidEndOnExit];
[addView addSubview:txtunm];


//Adding Two Button Login and Cancel into myView
btnadd=[UIButton buttonWithType:UIButtonTypeRoundedRect];
btnadd.frame=CGRectMake(50, 200, 100, 35);
[btnadd setTitle:@"ADD" forState:UIControlStateNormal];
[btnadd addTarget:self action:@selector(addClicked) forControlEvents:UIControlEventTouchUpInside];
[addView addSubview:btnadd];

btnshow=[UIButton buttonWithType:UIButtonTypeRoundedRect];
btnshow.frame=CGRectMake(180, 200, 100, 35);
[btnshow setTitle:@"SHOW" forState:UIControlStateNormal];
[btnshow addTarget:self action:@selector(showClicked) forControlEvents:UIControlEventTouchUpInside];
[addView addSubview:btnshow];

self.view=addView;


}

-(void) rmkeyboard
{
[txtuid resignFirstResponder];
[txtunm resignFirstResponder];
}
-(void)readData
{
NSString *query = [NSString stringWithString:@"select * from user_table"];
sqlite3_stmt *selectStatement;

uidarray = [[NSMutableArray alloc] init];
unmarray = [[NSMutableArray alloc] init];
int userid;
NSString *username;

int i=0;
if (sqlite3_prepare_v2([Database sharedInstance], [query UTF8String], -1, &selectStatement, NULL) == SQLITE_OK)
{
while (sqlite3_step(selectStatement)== SQLITE_ROW)
{
userid = sqlite3_column_int(selectStatement, 0);
username = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectStatement, 1)];


[uidarray addObject:[NSString stringWithFormat:@"%d",userid]];
[unmarray addObject:username];

NSLog(@"id=%@",[uidarray objectAtIndex:i]);

NSLog(@"unm=%@",[unmarray objectAtIndex:i]);
i++;

}
sqlite3_finalize(selectStatement);
}
}

-(void) showClicked
{
printf("Hello... showClicked");
//Tableview
mytabView = [[[UITableView alloc] initWithFrame:CGRectMake(0, 20, 320, 300) style:UITableViewStylePlain] autorelease];
[mytabView setDataSource:self];
[addView addSubview:mytabView];
[self readData];

}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [uidarray count];
}
// Return a cell for the specified index path
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"any-cell"];
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:@"any-cell"] autorelease];
}

CGFloat height=[tableView rowHeight];
cellLbl1=[[UILabel alloc]initWithFrame:CGRectMake(20, 0,60, height)];
cellLbl2=[[UILabel alloc]initWithFrame:CGRectMake(150, 0,100, height)];
cellLbl1.text=[uidarray objectAtIndex:[indexPath row]];
cellLbl2.text=[unmarray objectAtIndex:[indexPath row]];
[cell addSubview:cellLbl1];
[cell addSubview:cellLbl2];
return cell;
}

-(void) addClicked
{
NSLog(@"Add Dabavyu...");
sqlite3_stmt *insertStmt;

NSString *suid = txtuid.text;
NSInteger iuid = [suid intValue];

NSString *sunm = [NSString stringWithFormat:@"%@",txtunm.text];

NSString *insertQuery = [NSString stringWithFormat:@"insert into user_table values (%d,'%@');",iuid,sunm];

NSLog(@"int Query= %@",insertQuery);

if (sqlite3_prepare_v2([Database sharedInstance], [insertQuery UTF8String], -1, &insertStmt, NULL) != SQLITE_OK)
{
NSLog(@"Inserting Failed....!!!!");
return;
}

sqlite3_exec([Database sharedInstance], [insertQuery UTF8String], NULL, NULL, NULL);

}



- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}

- (void)viewDidUnload { }


- (void)dealloc {
[super dealloc];
}

@end

我想在 Controller 文件中使用同一个对象将数据插入数据库表user_table。我已经给出了应用程序的完整源代码。

我收到警告从不兼容的指针类型传递'sqlite3_prepare_v2'的参数1并且因此我无法从cnrtl文件打开到数据库的连接,请指导我如何解决它。

请帮助我。我是 iPhone 编程的初学者。

最佳答案

创建一个单例对象,如下所示:

在头文件中:

+(Database*)sharedInstance;

在实现文件中:

static Database* dbase = nil;

+(Database*)sharedInstance
{
if (dbase == nil)
{
dbase = [[Database alloc] init];
}
return dbase;
}

当你想调用数据库时,只需使用方法获取数据库对象
[数据库共享实例]

关于iphone - 如何在委托(delegate)和 Controller 文件中使用自定义数据库 header 的相同对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9112706/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com