在iOS中切换视图时,SQlite更新无效

时间:2012-10-02 07:28:50

标签: ios database xcode sqlite

我有一个收藏夹视图,它从sqlite数据库加载数据。它显然会加载进入单元格。

“收藏夹”视图类名为FavReal。我已经启用了canEditRowAtIndexPath,其操作是从数据库中删除条目并将其从表View中删除。它工作正常!我还有一个清除所有收藏夹按钮,正确删除所有条目。

现在,如果我点击一个单元格,它会转到另一个名为Details22视图的视图。在此视图中,我将获得所选单元格的详细信息,并且可以正常工作。

现在点击一个条目并返回收藏夹视图。如果我尝试通过滑动手势或清除所有按钮删除条目。它不起作用:S没有错误没有任何东西它只是不会从数据库中删除它,只是立即从表视图中删除它。

这是我的代码。

/ * FavReal.m * /

//
//  FavReal.m
//  AuthorsApp
//
//  Created by georges ouyoun on 8/16/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "FavReal.h"
#import <sqlite3.h>
#import "Author.h" 
#import "Details22.h"
#import "AuthorVC.h"
@interface FavReal ()

@end

@implementation FavReal
@synthesize textLabel2;
@synthesize theFav;
@synthesize author; 
NSString *authorNAme;
NSString *authorNAme3 , *authorNAme4;
NSString *authorFav;
NSString *PathDB;

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"entered the cellForRowAtIndexPath");
    static NSString *CellIdentifier2 = @"FavoritesCell";

    UITableViewCell *cell2 = [tableView dequeueReusableCellWithIdentifier:CellIdentifier2];
            NSLog(@"Break before the if");
    if (cell2 == nil) {
        NSLog(@"Entered the nil cell 1 ");
        cell2= [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier2];
        NSLog(@"Entered the nil cell 2 ");
    }

    Author *author8 = [self.theFav objectAtIndex:indexPath.row];
    NSLog(@"Author initialized");
    cell2.textLabel.text = author8.title;
    NSLog(@"This is the author8.title variable %@" , author8.title);
    NSLog(@"Cell2 is initialized");
 //   NSString *cellName = cell2.textLabel.text;

 //   [theFav release];
        return cell2;

}

-(void)viewWillAppear:(BOOL)animated{
//    [self.tableView cell];
    NSLog(@"§§§§§§§§§§§§§ VIew will appear phase 1 §§§§§§§§§§§§§§§§");

    [self authorList2];
    [self.tableView reloadData] ;
    NSLog(@"§§§§§§§§§§§§§ VIew will appear §§§§§§§§§§§§§§§§");
   [self viewDidLoad];
}

- (void)viewDidLoad
{
      NSLog(@"§§§§§§§§§§§§§ ViewDidLoad §§§§§§§§§§§§§§§§");
    UIBarButtonItem *nextButton = [[UIBarButtonItem alloc]
                                   initWithTitle:@"Clear All Favorites"
                                   style:UIBarButtonItemStyleBordered

                                   target:self
                                   action:@selector(deleteSomeStuff)];

    [[self navigationItem] setLeftBarButtonItem:nextButton];

    [nextButton release], nextButton = nil;

    [self authorList2];
    [super viewDidLoad];

}

- (void)viewDidUnload
{

    NSLog(@"§§§§§§§§§§§§§ ViewDid UN-Load §§§§§§§§§§§§§§§§");

    [self setTextLabel2:nil];
    [ClearBu release];
    ClearBu = nil;
    [super viewDidUnload];

}

-(void) viewWillDisappear:(BOOL)animated{

}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
#warning Potentially incomplete method implementation.
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
#warning Incomplete method implementation.
    int rowCount;

     rowCount = theFav.count;
    return rowCount;
}

-(NSMutableArray *) authorList2{

    NSFileManager *fileManager = [NSFileManager defaultManager];

    NSLog(@"1");
    theFav = [[NSMutableArray alloc] initWithCapacity:1000000];

    @try {
        NSLog(@"1 alpha:");

        BOOL success = [fileManager fileExistsAtPath:PathDB];
        NSLog(@"1 gamma");
        if(!success)
        {
            NSLog(@"2");
            NSLog(@"Cannot locate database file '%@'.", PathDB);
        }
        NSLog(@"Success");
        if(!(sqlite3_open([PathDB UTF8String], &db2) == SQLITE_OK))
        {
            NSLog(@"3");
            NSLog(@"An error has occured: %@", sqlite3_errmsg(db2));

        }

        NSLog(@"Database opened");
        // const char *sql = "SELECT F_Keyword FROM wordss";  
        const char *sql2 = "SELECT Name FROM Fav";

        sqlite3_stmt *sqlStatement2;
        if(sqlite3_prepare(db2, sql2, -1, &sqlStatement2, NULL) != SQLITE_OK)
        {
            NSLog(@"Problem with prepare statement:  %@", sqlite3_errmsg(db2));
        }else{
            while (sqlite3_step(sqlStatement2)==SQLITE_ROW) {
              //  NSLog(@"Probleme not with the query but in here!!");
                Author * author2 = [[Author alloc] init];
                //author2.fav = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement2,2)];
                author2.title = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement2,0)];

               // authorFav=author2.title;              
                [theFav addObject:author2];

            }
        }
    }
    @catch (NSException *exception) {
        NSLog(@"Problem with prepare statement:  %@", sqlite3_errmsg(db2));
    }
    @finally {

        return theFav;
    }
}


-(void)deleteSomeStuff{
    NSLog(@"Delete Button Clicked");
    @try {
     //   NSLog(@"This is the authorName2 variable %@",authorNAme2);

        sqlite3_stmt *compiled_statement1;

        if(sqlite3_open([PathDB UTF8String], &db2) == SQLITE_OK) {

            NSString *formatedSql = [NSString stringWithFormat:@"DELETE FROM Fav"];

            const char *sql = [formatedSql UTF8String];
            NSLog(@" !!!!!!!! In the middle of it !!!!!!!!!!!!");
            if (sqlite3_prepare_v2(db2, sql, -1, &compiled_statement1, NULL) != SQLITE_OK) {
                NSLog(@"!!!!!!!!!!!!!!!!!!!ERRRRROOOOOOORRRRRRRRR!!!!!!!!!!!!!!!!!!!!!!!!!");

            }

            NSLog(@"This is the query %@",formatedSql);


            int success = sqlite3_step(compiled_statement1);

            if (success != SQLITE_ERROR) {
                NSLog(@"Successfully Deleted!");
                sqlite3_last_insert_rowid(db2);
            }

            if(sqlite3_prepare(db2, sql, -1, &compiled_statement1, NULL) != SQLITE_OK)
            {
                NSLog(@"Problem with prepare statement:  %@", sqlite3_errmsg(db2));

            }else{

                NSLog(@"Got in the else tag where pictures should change ");

                while (sqlite3_step(compiled_statement1)!=SQLITE_OK) {

                    NSLog(@"Got in the while tag");
                    break;
                    }
                }
            }

       // NSArray *arr;
        [self.theFav removeAllObjects]; 
        [self.tableView reloadData];

        }

    @catch (NSException *exception) {

        NSLog(@"Problem with prepare statement:  %@", sqlite3_errmsg(db2));
    }
    @finally {
        sqlite3_close(db2);
    }

}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

#pragma mark - Table view delegate

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if(editingStyle == UITableViewCellEditingStyleDelete)
    {
        @try{
            if(!(sqlite3_open([PathDB UTF8String], &db2) == SQLITE_OK))
            {
                NSLog(@"3");
               // NSLog(@"Could not open Db2", sqlite3_errmsg(db2));

            }
            else {
                NSLog(@"Db2 is opened");
            }
            NSIndexPath *indPath7= [NSIndexPath indexPathForRow:indexPath.row inSection:0]; 
            UITableViewCell *cell7 = [tableView cellForRowAtIndexPath:indPath7]; 
            NSString *cellText7 = cell7.textLabel.text;

          //  NSLog(@"§§§§§§§§§§§§§§§§§ This is the cell text §§§§§§§§§§" , cellText3);
            sqlite3_stmt *sqlStatement7;
            NSString *titleString = [[[NSString alloc] initWithFormat:@"%d",indexPath.row] autorelease];

            //const char *sql3 = ["DELETE FROM Fav WHERE rowid = '%@'" , titleString]  ;

            NSString *formatedSql3 = [NSString stringWithFormat:@"DELETE FROM Fav WHERE Name = '%@'" ,cellText7];
           // const char *formatedSql3 = [@"DELETE FROM Fav WHERE rowid = '%@'",titleString];

            NSLog(@"This is the DELETE Query %@", formatedSql3);
            const char *sql3 = [formatedSql3 UTF8String];
            NSLog(@"This is the titleString Variable %@ " , titleString);

            if(sqlite3_prepare(db2, sql3, -1, &sqlStatement7, NULL) != SQLITE_OK)
        {
            NSLog(@"Problem with prepare statement:  %@", sqlite3_errmsg(db2));
        }
            else{

                int successS = sqlite3_step(sqlStatement7);
                if (successS != SQLITE_DONE) {
                    NSLog(@"An error Has occured during the delete of the specific record");
                }
                else{

                    NSLog(@"Update Database successfull!");
                }
            }
        }    
                @catch (NSException *exception) {
                    NSLog(@"Problem with prepare statement:  %@", sqlite3_errmsg(db2));
                }

                @finally {
                    //sqlite3_finalize(sql);
                  //  sqlite3_close(db2);
                    //return theFav;
                }
            [self.theFav removeObjectAtIndex:indexPath.row];
            [self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];

    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    NSIndexPath *indPath3 = [NSIndexPath indexPathForRow:indexPath.row inSection:0]; 
    UITableViewCell *cell3 = [tableView cellForRowAtIndexPath:indPath3]; 
    NSString *cellText3 = cell3.textLabel.text;

  //  NSLog(@"This is at first : %@" , authorNAme);
  //   NSString *titleString2 = [[[NSString alloc] initWithFormat:@"Element row number :  %d",indexPath.row] autorelease];
    NSLog(@"This is the showDetailsForIndexPath");

    Details22 * vc4 = [self.storyboard instantiateViewControllerWithIdentifier:@"Details22"];
    //FavReal* author;
    NSLog(@"This is the showDetailsForIndexPath 2");

    @try{
            if(sqlite3_open([PathDB UTF8String], &db2) == SQLITE_OK) {

        NSString *titleString3 = [[[NSString alloc] initWithFormat:@"Element row number :  %d",indexPath.row] autorelease];
        NSLog(@"This is the row number chosen %@",titleString3);

       NSString *formatedSql333 = [NSString stringWithFormat:@"Select * from Sheet1 where field3 = '%@'" , cellText3 ];
                const char *formatedSql3333 = [formatedSql333 UTF8String];

        NSLog(@"This is the SQLite Approriate Query %@",formatedSql333);

        sqlite3_stmt *sqlStatement3;

        NSString *SearchedItem = cellText3;
        NSLog(@"This is the SearchedITem Variable %@" , SearchedItem);

        if(sqlite3_prepare(db2, formatedSql3333, -1, &sqlStatement3, NULL) != SQLITE_OK)
    {
            NSLog(@"Problem with prepare statement:  %@", sqlite3_errmsg(db2));
    }else{

     while (sqlite3_step(sqlStatement3)!=SQLITE_ERROR) {

         NSLog(@"Entered the While tag");   
         NSString *SearchedItem = cellText3;
         NSLog(@"This is the SearchedITem Variable %@" , SearchedItem);


                Author * author3 = [[Author alloc] init];
         NSLog(@" Debug 1  ");

                author3.name = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement3,2)];
                  NSLog(@" Debug 2  ");

                NSLog(@"This is the author.name in the FavReal %@" , author3.name);

                author3.title = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement3,3)];
         NSLog(@"This is the author.TITLE in the FavReal %@" , author3.title);

                author3.genre = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement3, 6)];
         NSLog(@"This is the author.GENRE in the FavReal %@" , author3.genre);
         NSLog(@"This is the authorName before %@", authorNAme);
         NSLog(@"This is the authorName2 before %@", authorNAme2);
         authorNAme = author3.genre;
         authorNAme2 = author3.name;

         NSLog(@"This is the authorName after %@", authorNAme);
         NSLog(@"This is the authorName2 after %@", authorNAme2);

         NSLog(@"Before the break");
         NSLog(@"Before the animation part");
         [self.navigationController pushViewController:vc4 animated:true];   
         NSLog(@"Passed the should animate part");

         break;
         NSLog(@"After the break");
     }     
               }
    }
    }

    @catch (NSException *exception) {
        NSLog(@"Problem with prepare statement:  %@", sqlite3_errmsg(db2));
    }
    @finally {
        sqlite3_close(db2);
        NSLog(@"The database should NOT be closed here");
    }
}

- (UITableViewCellAccessoryType)tableView:(UITableView *)tableView accessoryTypeForRowWithIndexPath:(NSIndexPath *)indexPath {

    //return UITableViewCellAccessoryDetailDisclosureButton;
    return UITableViewCellAccessoryDisclosureIndicator;
}

- (void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath {

    [self tableView:tableView didSelectRowAtIndexPath:indexPath];
}

- (void)dealloc {
    [theFav release];
    [self release];
    [textLabel2 release];
    [textLabel2 release];
    [ClearBu release];
    [super dealloc];
}
- (IBAction)ClearButtonAction:(id)sender {

    NSLog(@"Clear Button is Clicked");
}
@end

/ * Details22.m * /

//
//  Details.m
//  AuthorsApp
//
//  Created by georges ouyoun on 7/17/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "AppDelegate.h"
#import "Details22.h"
#import "Author.h"
#import "AuthorVC.h"
#import <sqlite3.h>
#import "FavReal.h"
//#import "MTPopupWindow.h"


@interface Details22 ()

@end

@implementation Details22
//@synthesize Favo;
@synthesize text2;
@synthesize WebV2;
@synthesize labelText;
@synthesize selectedAuthors;
@synthesize author , infoRequest;
NSUInteger textFontSize2 = 20;
NSString *PathDB; 
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    NSLog(@"In the viewDidLoad this is the current value of the textFontSize %d" , textFontSize2);

    NSString * htmlString = [NSString stringWithFormat:@"\
                             <html>\
                             <body>\
                             <p dir='rtl' style = 'font-size:40px;'> %@ </p>\
                             </body>\
                             </html>",authorNAme];


    [self.WebV2 setScalesPageToFit:YES];
    [self.WebV2 loadHTMLString:htmlString baseURL:nil];

    self.text2.text = authorNAme2;

    /* ////////////////////////////////////////////         This is where the label text APPearsssssssss       ///////////////////////////          */

    NSLog(@"Everything is ok now !");

}
- (void)viewDidUnload
{
    //  [self setLabelText:nil];
    NSLog(@"U have entered view did unload in Details22");

    //[FavReal initialize];

    [self setText2:nil];

    [self setWebV2:nil];

    [sizeFontFromStepper release];
    sizeFontFromStepper = nil;
    [super viewDidUnload];

    //[self setLabelText:Nil];
    //[AuthorVC load];

    //[self release];
   // NSLog(@" FAvReal should have been initialised ");
    // Release any retained subviews of the main view.
}

-(void)viewWillAppear:(BOOL)animated
{ 
    NSLog(@"U have entered the viewWillAppear tag");
}

-(void) viewWillDisappear:(BOOL)animated{

      NSLog(@"This is the view will disappear tag in Details22");

}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return YES;
}

- (void)dealloc {
    [labelText release];

    [text2 release];
   // [fontStep release];
    [WebV2 release];
    [sizeFontFromStepper release];
   // [sizeFontFromStepper release];
    [super dealloc];
}

-(void)loadHTMLString:(int)textFontSize2
{
    NSString * htmlString = [NSString stringWithFormat:@"\
                             <html>\
                             <body>\
                             <p dir='rtl' style = 'font-size:%dpx;'> %@ </p>\
                             </body>\
                             </html>",textFontSize2,authorNAme];

    NSLog(@"This is the loadHTMLString function with a textFonSize of %d" , textFontSize2);

    //[self.WebV setScalesPageToFit:YES];
    [self.WebV2 loadHTMLString:htmlString baseURL:nil];

}
- (IBAction)loadHtmlNewFontSize:(int)textFontSize2 {

    textFontSize2 = sizeFontFromStepper.value;

    [self loadHTMLString:textFontSize2];

    NSLog(@"This is textFontSize %d" , textFontSize2);
}          

@end

任何人?

1 个答案:

答案 0 :(得分:0)

经过很多腰部时间!!!唯一最简单的解决方案是在didSelectRowAtIndexPath方法中,在@finally, sqlite3_finalize(stmt) 中添加FavReal.m。 这就是整个问题!