如何在iPhone中将列值检索到另一个tableview?

时间:2013-06-03 07:57:21

标签: iphone ios objective-c sqlite

我是IOS的初学者,我在我的数据库中有存款表和费用表我想从存款表中检索存款金额,费用金额从费用表中检索到两个表格视图,一个用于存款金额表视图,另一个是在单个屏幕中的费用金额表视图。以下是我在此

中的dbmodelclass.h
#import <UIKit/UIKit.h>
#import <sqlite3.h>
@interface dbModelClass : UIViewController
{
    NSMutableDictionary *readDic;
    NSMutableArray *readArray;
}
+(NSString *)connectDb;
+(BOOL)createTable;
+(BOOL)createTable3;
+(int)saveData:(NSMutableArray *)data;
+(int)saveData2:(NSMutableArray *)data;
+(NSMutableArray *)getData;
@end

这是我的dbmodelclass.m

#import "dbModelClass.h"
#import "Expences.h"
@implementation dbModelClass;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
   self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
   if (self)
   {
      // Custom initialization
   }
   return self;
}

- (void)didReceiveMemoryWarning
{
   // Releases the view if it doesn't have a superview.
   [super didReceiveMemoryWarning];

   // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
   [super viewDidLoad];
   // Do any additional setup after loading the view from its nib.
}
+(NSString *)connectDb
{
   NSArray *docDir=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,          NSUserDomainMask, YES);
   NSString *dbFolder=[docDir objectAtIndex:0];
   NSFileManager *manager=[NSFileManager defaultManager];
   if (![manager fileExistsAtPath:dbFolder])
   {
       [manager createDirectoryAtPath:dbFolder withIntermediateDirectories:YES attributes:nil error:nil];
   }
   NSString *dbPath=[dbFolder stringByAppendingPathComponent:@"fappDB.sqlite"];
   if (![manager fileExistsAtPath:dbPath])
   {
       [manager copyItemAtPath:[[[NSBundle mainBundle]resourcePath]stringByAppendingPathComponent:@"fappDB.sqlite"] toPath:dbPath  error:nil];
   }
   NSLog(@"%@",dbPath);
   return dbPath;
}

+(BOOL)createTable
{
   NSString *dbpath=[dbModelClass connectDb];
   sqlite3 *dbObj;
   if (sqlite3_open([dbpath UTF8String], &dbObj)==SQLITE_OK)
   {
      sqlite3_stmt *stmt=nil;
      const char *sql="create table deposit(deposit_amount VARCHAR,remarks VARCHAR)";
      sqlite3_prepare_v2(dbObj, sql, -1, &stmt, nil);
      if (sqlite3_step(stmt)==SQLITE_DONE)
      {
          NSLog(@"tabel created successfull");
      }
      else
      {
         NSLog(@"tabel already created");
      }
      sqlite3_finalize(stmt);
      sqlite3_close(dbObj);
   }   
   return YES;
} 
+(BOOL)createTable3;
{
   NSString *dbpath=[dbModelClass connectDb];
   sqlite3 *dbObj;
   if (sqlite3_open([dbpath UTF8String], &dbObj)==SQLITE_OK)
   {
       sqlite3_stmt *stmt=nil;
       const char *sql="create table expense2(expense_title VARCHAR,description VARCHAR,amount VARCHAR,paidcash VARCHAR,date VARCHAR,remarks VARCHAR)";
       sqlite3_prepare_v2(dbObj, sql, -1, &stmt, nil);
       if (sqlite3_step(stmt)==SQLITE_DONE)
       {
           NSLog(@"tabel created successfull");
       }
       else
       {
           NSLog(@"tabel already created");
       }
       sqlite3_finalize(stmt);
       sqlite3_close(dbObj);
    }
    return YES;
}

+(int)saveData:(NSMutableArray *)data
{
sqlite3 *dbObj;
sqlite3_stmt *stmt=nil;
NSString *dbPath=[dbModelClass connectDb];
const char *sql=[[NSString stringWithFormat:@"insert into deposit(deposit_amount,remarks) values(\"%@\",\"%@\")",[data objectAtIndex:0],[data objectAtIndex:1]]UTF8String];

if (sqlite3_open([dbPath UTF8String], &dbObj)==SQLITE_OK)
{
    sqlite3_bind_text(stmt, 1, [[data objectAtIndex:0]UTF8String], -1, SQLITE_TRANSIENT);
    sqlite3_bind_text(stmt, 2, [[data objectAtIndex:1]UTF8String], -1, SQLITE_TRANSIENT);


    sqlite3_prepare_v2(dbObj, sql, -1, &stmt, nil);
    if (sqlite3_step(stmt)==SQLITE_DONE)
    {
      NSLog(@"data insertion stmnt executed properly");
       }
       else
          NSLog(@"data insertion stmnt not executed");

          sqlite3_finalize(stmt);
           sqlite3_close(dbObj);

  }
return sqlite3_last_insert_rowid(dbObj);
} 

+(int)saveData2:(NSMutableArray *)data
{
sqlite3 *dbObj;
sqlite3_stmt *stmt=nil;
NSString *dbPath=[dbModelClass connectDb];
const char *sql=[[NSString stringWithFormat:@"insert into expense2(expense_title,description,amount,paidcash,date,remarks) values(\"%@\",\"%@\",\"%@\",\"%@\",\"%@\",\"%@\")",[data objectAtIndex:0],[data objectAtIndex:1],[data objectAtIndex:2],[data objectAtIndex:3],[data objectAtIndex:4],[data objectAtIndex:5]]UTF8String];

if (sqlite3_open([dbPath UTF8String], &dbObj)==SQLITE_OK)
{
    sqlite3_bind_text(stmt, 1, [[data objectAtIndex:0]UTF8String], -1, SQLITE_TRANSIENT);
    sqlite3_bind_text(stmt, 2, [[data objectAtIndex:1]UTF8String], -1, SQLITE_TRANSIENT);
    sqlite3_bind_text(stmt, 3, [[data objectAtIndex:2]UTF8String], -1, SQLITE_TRANSIENT);
    sqlite3_bind_text(stmt, 4, [[data objectAtIndex:3]UTF8String], -1, SQLITE_TRANSIENT);
    sqlite3_bind_text(stmt, 5, [[data objectAtIndex:4]UTF8String], -1, SQLITE_TRANSIENT);
    sqlite3_bind_text(stmt, 6, [[data objectAtIndex:5]UTF8String], -1, SQLITE_TRANSIENT);

    sqlite3_prepare_v2(dbObj, sql, -1, &stmt, nil);
    if (sqlite3_step(stmt)==SQLITE_DONE)
    {
        NSLog(@"data insertion stmnt executed properly");
    }
    else
        NSLog(@"data insertion stmnt not executed");

    sqlite3_finalize(stmt);
    sqlite3_close(dbObj);

 }
return sqlite3_last_insert_rowid(dbObj);
}
-(NSMutableArray *)getData
{
sqlite3 *dbobj;
NSString *dbpath  =[dbModelClass connectDb];
readArray=[[NSMutableArray alloc]init];
if(sqlite3_open([dbpath UTF8String], &dbobj)==SQLITE_OK)
{
    sqlite3_stmt *statement=nil;

    //**** NSString *string=@"SELECT name FROM emptable";
    NSString *string=@"SELECT *FROM deposit WHERE deposit_amount";
    const char *query=[string UTF8String];
    if(sqlite3_prepare_v2(dbobj, query, -1, &statement, NULL)==SQLITE_OK)
    {
        while (sqlite3_step(statement)==SQLITE_ROW)
        {
    readDic=[[NSMutableDictionary alloc] init];

            [readDic setObject:[NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 0)] forKey:@"deposit_amount"];
            // NSString *aName=[NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 0)];
            // NSString *pwd=[NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 1)];
            //[readDic setObject:[NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 1)] forKey:@"remarks"];
            //  [readArray addObject:aName];
            // [readArray1 addObject:pwd];
            [readArray addObject:readDic];
            // NSLog(@"%@",readDic);
        }
    }
    sqlite3_finalize(statement);
}
NSLog(@"%@",readArray);
sqlite3_close(dbobj);
return readArray;
}



 - (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

@end

这是我的netviewcontroller.h

#import <UIKit/UIKit.h>

@interface NetViewController : UIViewController<UITableViewDataSource,UITableViewDelegate>//DepositTable *depositCo
{
IBOutlet  UILabel *depositLabel,*expenseLabel,*netvalueLabel;
IBOutlet  UITextField *netvalueText;
IBOutlet UITableView *depositTable,*expenseTable;


}
@property (strong, nonatomic) UINavigationController *navigationController;
@property(strong,nonatomic)UILabel  *depositLabel,*expenseLabel,*netvalueLabel;
@property(strong,nonatomic)UITextField *netvalueText;
@property(strong,nonatomic)UITableView *depositTable,*expenseTable;



-(IBAction)netvalue:(id)sender;

@end

我的netviewcontroller.m

#import "NetViewController.h"
#import "dbModelClass.h"
@interface NetViewController ()

@end

@implementation NetViewController
@synthesize depositLabel,expenseLabel,netvalueLabel,depositTable,expenseTable,netvalueText;


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
    // Custom initialization
}
return self;
}

- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
[dbModelClass connectDb];
[dbModelClass getData];
NSMutableArray *issuesArray = [[NSMutableArray alloc]init];  [dbModelClass financeappDB:@"SELECT * FROM  deposit" resultsArray:issuesArray];
NSLog(@"contents count:%d",[issuesArray count]);

}

- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(IBAction)netvalue:(id)sender
{

}
@end

请帮帮我

2 个答案:

答案 0 :(得分:0)

你做得不好:)。

  1. 为什么要创建一个继承自UIViewController的对象来管理数据库,你可以创建一个继承自NSObject的对象。

  2. 在getData方法中,您只是要求存放表的数据,您应该将参数(表名和数量)传递给您的方法,以了解您是否需要来自存款表或费用2表的数据。

  3. 最后在NetViewController类中,你可以这样做:

  4. ...

    [dbModelClass connectDb];
    NSArray *depositData =  [dbModelClass getDataWith....]; // here you fetch your database with deposit table and others param 
    
    NSArray * expenseData = [dbModelClass getDataWith....]; // Here you fetch your database with expensive table and others param 
    

    编辑回答:

    你可以这样做:

    -(NSMutableArray *)getDataForTable:(NSString *)tableName withAmount:(NSString *)amountName
    {
    sqlite3 *dbobj;
    NSString *dbpath  =[dbModelClass connectDb];
    readArray=[[NSMutableArray alloc]init];
    if(sqlite3_open([dbpath UTF8String], &dbobj)==SQLITE_OK)
    {
        sqlite3_stmt *statement=nil;
    
        //**** NSString *string=@"SELECT name FROM emptable";
    
       NSString *string = [NSString stringWithFormat:@"SELECT *FROM %@ WHERE %@",tableName,amountName];
    
       const char *query=[string UTF8String];
        if(sqlite3_prepare_v2(dbobj, query, -1, &statement, NULL)==SQLITE_OK)
        {
            while (sqlite3_step(statement)==SQLITE_ROW)
            {
        readDic=[[NSMutableDictionary alloc] init];
    
                [readDic setObject:[NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 0)] forKey:@"deposit_amount"];
                // NSString *aName=[NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 0)];
                // NSString *pwd=[NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 1)];
                //[readDic setObject:[NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 1)] forKey:@"remarks"];
                //  [readArray addObject:aName];
                // [readArray1 addObject:pwd];
                [readArray addObject:readDic];
                // NSLog(@"%@",readDic);
            }
        }
        sqlite3_finalize(statement);
    }
    

    添加此
    -(NSMutableArray *)getDataForTable:(NSString *)tableName withAmount:(NSString *)amountName

    中的dbModelClass.h

    现在你可以通过传递表名和金额来调用NetViewController中的这个方法:

    [dbModelClass connectDb];
    NSArray * depositResult = [dbModelClass getDataWith:@"deposite" amountName:@"deposit_amount"];
    

    //通过传递适当的名称为另一个表做同样的事情。

    PS:此代码未经过测试,您应该重构它,它只是为了向您展示如何传递方法的参数

答案 1 :(得分:0)

您的问题有几种解决方案。

最好的解决方案实际上是最简单的。

主视图控制器,带有两个嵌入式tableViewControllers,每个都显示和管理数据库中的一个表。

在viewDidLoad中,您将创建每个tableViewController的实例,设置它的框架以找到主视图的所需坐标并将其添加到主视图。

现在,您可以为每个表创建一个干净简单的委托模型,如果您在主视图控制器中保留每个tableViewController的实例(分配为属性),您将能够从主视图与每个表进行通信

更复杂的方法是将两个tableView添加到主视图xib,将它们连接到数据源并委托主viewController中的方法,然后测试对委托方法的每个调用以确定哪个tableView称为方法。我已经做到了,但从长远来看,这是很痛苦的。