适用于初学者的iOS Sqlite数据库指南

时间:2016-12-26 11:35:26

标签: ios objective-c database sqlite cocoa-touch

我也是iOS技术的初学者。根据我的标题,可能这个问题对每个新开发者都有帮助。

欢迎所有人编辑我的答案并纠正我或者提出你自己的答案来提高我们的知识。

在下面的例子I中考虑

  

1)一个表名是“学生”
  2)以下是字段名称
   - 名字
   - 姓氏
   - 地址
   - 出生日期

在这里,我们可以从表中应用操作操作,如“添加”,“更新”,“删除”和“获取”记录。

更新:

根据其他用户的回答,我们也可以按CoreData进行操作。但是CoreDataSQLite更快更容易吗?如果数据很复杂,那么我们如何按CoreData进行管理?

4 个答案:

答案 0 :(得分:0)

首先我们需要创建SQLite数据库和表。我在想有很多方法可以创建数据库和表格,但最充分的方式是我正在使用

1)安装Firefox并安装附加组件 https://addons.mozilla.org/en-US/firefox/addon/sqlite-manager/

2)创建数据库
- 继续使用Firefox - >工具 - > SQLite经理
- 左上角选择第3个 - >新数据库或在菜单栏上,选择“数据库” - >新数据库
- 提供数据库名称“student”并在项目中保存正确的位置。

3)创建表格 - 左侧菜单 - >选择“Tables(0)” - >右键单击 - 创建表格或在菜单栏上选择“表格” - >创建表
- 授予表名“student_info”并在项目中保存正确的位置。

Belo是执行操作操作的代码。

#import <Foundation/Foundation.h>
#import "sqlite3.h"

@interface SQLDb : NSObject
{
    sqlite3 *_database;
    NSString *savedDate;
}

@property (readwrite) sqlite3* _database;
@property (nonatomic, strong) NSString *savedDate;

+(SQLDb *) initEngine;
+ (SQLDb*) database ;
+(void)releaseEngine;
- (void) executeQuery:(NSString *)query;

-(void) insertRecordInStuentTable:(NSMutableDictionary *) dicOfStudent;
-(NSMutableArray *) getRecordFrom_bannerTable;
-(void)updateNameOfStuden:(NSString *)studentName withRollNumber:(NSString *)strRollNumber;
-(void) deleteAllDataFrom_Student_Table;

对于.m文件

#import "SQLDb.h"

@implementation SQLDb

////Getters / Setters
@synthesize _database, savedDate;

static SQLDb* _database = nil;

//start for initialization of database

#pragma mark -  Initialization Methods -

+ (SQLDb*)database
{
    if (_database == nil)
        _database = [[SQLDb alloc] init];

    return _database;
}

+(SQLDb *) initEngine
{
    if ( !_database )
    {
        NSString *databaseName = @“student.sqlite";
        [SQLDb createEditableCopyOfFileIfNeeded:databaseName];
        sqlite3 *db = nil;
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentsDirectory = [paths objectAtIndex:0];
        NSString *path = [documentsDirectory stringByAppendingPathComponent:databaseName];
        NSLog(@"DB path - %@", path);
        const char* dbName = [path UTF8String];
        if ( sqlite3_open(dbName,&db) != SQLITE_OK )
        {
            NSException* initException;
            initException = [NSException exceptionWithName:@"SQL Exception" reason:@"Database Initialization Failed" userInfo:nil];
            @throw initException;
        }

        _database = [[self allocWithZone: NULL] init] ;
        _database._database = db;
    }

    return _database;
}

+ (void)createEditableCopyOfFileIfNeeded:(NSString *)fileName
{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSError *error;
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:fileName];
    BOOL success = [fileManager fileExistsAtPath:writableDBPath];
    if (success)
        return;

    NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:fileName];
    success = [fileManager copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error];

    NSLog(@"Database Path - %@", writableDBPath);
    if (!success)
        NSLog(@"Failed to create writable database file with message '%@'.", [error localizedDescription]);
}

-(void) executeQuery:(NSString *)query
{
    sqlite3_stmt *statement;
    if (sqlite3_prepare_v2(_database, [query UTF8String], -1, &statement, nil) == SQLITE_OK)
    {
        char *selectQuery = sqlite3_mprintf([query UTF8String]);
        sqlite3_free(selectQuery);
        sqlite3_step(statement);
        sqlite3_finalize(statement);
    }
}

+(void) releaseEngine
{
    sqlite3_close(_database._database);
    _database._database = nil;
    _database = nil;
}


//==================================

-(void) insertBannerInTable:(NSMutableDictionary *) dicOfStuent
{
    int ret;
    const char *sql = "INSERT INTO `student` (‘firstname’, ‘lastname’, ‘bdate’, ‘address’) VALUES (?, ?, ?, ?);";

    sqlite3_stmt *insStmt = NULL;
    if ( !insStmt )
        if ( (ret = sqlite3_prepare_v2(_database, sql, -1, &insStmt, NULL)) != SQLITE_OK ) {

            NSLog(@"Proble to insert record in student");
        }

    // bind values

    sqlite3_bind_text(insStmt, 1, [[NSString stringWithFormat:@"%@", [dicOfStuent objectForKey:@"firstname"]] UTF8String], -1, SQLITE_TRANSIENT);
    sqlite3_bind_text(insStmt, 2, [[NSString stringWithFormat:@"%@", [dicOfStuent objectForKey:@"lastname"]] UTF8String], -1, SQLITE_TRANSIENT);
    sqlite3_bind_text(insStmt, 3, [[NSString stringWithFormat:@"%@", [dicOfStuent objectForKey:@"bdate"]] UTF8String], -1, SQLITE_TRANSIENT);
    sqlite3_bind_text(insStmt, 4, [[NSString stringWithFormat:@"%@", [dicOfStuent objectForKey:@“address”]] UTF8String], -1, SQLITE_TRANSIENT);

    if ((ret = sqlite3_step(insStmt)) != SQLITE_DONE) {NSLog(@"error while inserting data in 'student' table");}
    sqlite3_reset(insStmt);
}


-(NSMutableArray *) getRecordFrom_StudentTable
{
    NSMutableArray *listofStudent = [[NSMutableArray alloc] init];
    sqlite3_stmt *statement = NULL;
    NSString *query = [NSString stringWithFormat:@"SELECT * FROM bannerTable"];
    if (sqlite3_prepare_v2(_database, [query UTF8String], -1, &statement, nil) == SQLITE_OK)
    {
        while (sqlite3_step(statement) == SQLITE_ROW)
        {
            //('banner_id', 'banner_image', 'banner_type', 'banner_description', 'banner_link') VALUES (?, ?, ?, ?, ?)

            char *mainIDChars = (char *) sqlite3_column_text(statement, 0);
            char *bnrIdChars = (char *) sqlite3_column_text(statement, 1);
            char *bnrImgChars = (char *) sqlite3_column_text(statement, 2);
            char *bnrTypChars = (char *) sqlite3_column_text(statement, 3);
            char *bnrDesChars = (char *) sqlite3_column_text(statement, 4);
            char *bnrLinkChars = (char *) sqlite3_column_text(statement, 5);

            NSString *mainID = @"", *advertisement_id  = @"", *advertisement_image = @"", *advertisement_type  = @"", *advertisement_description  = @"", *advertisement_link = @"";

            if(mainIDChars != NULL)
                mainID  = [[NSString alloc] initWithUTF8String:mainIDChars];
            if(bnrIdChars != NULL)
                advertisement_id  = [[NSString alloc] initWithUTF8String:bnrIdChars];
            if(bnrImgChars != NULL)
                advertisement_image  = [[NSString alloc] initWithUTF8String:bnrImgChars];
            if(bnrTypChars != NULL)
                advertisement_type  = [[NSString alloc] initWithUTF8String:bnrTypChars];
            if(bnrDesChars != NULL)
                advertisement_description  = [[NSString alloc] initWithUTF8String:bnrDesChars];
            if(bnrLinkChars != NULL)
                advertisement_link  = [[NSString alloc] initWithUTF8String:bnrLinkChars];

            NSMutableDictionary *dicOfStuent = [[ NSMutableDictionary alloc] init];
            [dicOfStuent setObject:mainID forKey:@"main_id"];
            [dicOfStuent setObject:advertisement_id forKey:@"advertisement_id"];
            [dicOfStuent setObject:advertisement_image forKey:@"advertisement_image"];
            [dicOfStuent setObject:advertisement_type forKey:@"is_image_url"];
            [dicOfStuent setObject:advertisement_description forKey:@"advertisement_description"];
            [dicOfStuent setObject:advertisement_link forKey:@"advertisement_link"];
            [listofStudent addObject:dicOfStuent];
        }
        sqlite3_finalize(statement);
    }

    return listofStudent;
}


-(void)updateNameOfStuden:(NSString *)studentName withRollNumber:(NSString *)strRollNumber
{
    int ret;
    const char *sql = "update user_Group_ChatList set is_online = ? where Jabber_id = ?;";
    sqlite3_stmt *updtStmt = NULL;
    if ( !updtStmt )
        if ( (ret = sqlite3_prepare_v2(_database, sql, -1, &updtStmt, NULL)) != SQLITE_OK ) {}

    // bind values
    sqlite3_bind_text(updtStmt, 1, [[NSString stringWithFormat:@"%@", strProductID] UTF8String], -1, SQLITE_TRANSIENT);
    sqlite3_bind_text(updtStmt, 2, [strTotalProduct UTF8String], -1, SQLITE_TRANSIENT);

    if ((ret = sqlite3_step(updtStmt)) != SQLITE_DONE) {NSLog(@"error while updating  QTY from ProductsCart Table");}
    sqlite3_reset(updtStmt);

}


-(void) deleteAllDataFrom_Student_Table
{
    int ret;
    const char *sql = "DELETE FROM student";

    sqlite3_stmt *dltStmt = NULL;
    if ( !dltStmt )
        if ( (ret = sqlite3_prepare_v2(_database, sql, -1, &dltStmt, NULL)) != SQLITE_OK ) {}

    if ((ret = sqlite3_step(dltStmt)) != SQLITE_DONE) {NSLog(@"Error : While Deleting Record From  user_Group_ChatList Table");}
    sqlite3_reset(dltStmt);
}

上面是.H和.M文件,可以帮助您管理SQLite数据库。

答案 1 :(得分:0)

如果您是iOS技术的初学者并希望学习本地存储管理,那么我建议您使用:FOO :FOO

Manage Local storage using Core Data

因为使用核心数据,您可以以对象和类的形式与本地数据库进行交互。

答案 2 :(得分:0)

根据你的问题,大多数人都说

Coredta is better than SQLite

当你使用附加工具使用SQLite时,我们需要做以下事情。我会清楚地解释你。

我的数据库名称是 - LoginRegistration.sqlite

我的数据库表名称是 - TblReg

我有登录屏幕。我有用户名和密码字段。我有登录和注册按钮。

当你点击注册按钮时,它会进入注册页面视图控制器,我们必须首先注册,然后我们必须保存数据,将数据插入我们的SQLite数据库。

为了实现SQLite,首先我们必须添加和导入sqlite3.h。

<强> DatabaseOne.h

 #import <Foundation/Foundation.h>
 #import <sqlite3.h>
 @interface DatabaseOne : NSObject{
 sqlite3 *SQLDB;
 NSString *dbName;
 }

 +(DatabaseOne *)sharedDB;

 -(id)init;
 - (id)initWithName:(NSString *)dbname;
 - (void)createDB:(NSString *)dbname;
 - (NSString *)getDBPath;
 - (void)copyDatabaseIfNeeded;
 - (BOOL)executeQuery:(NSString *)query;
 - (NSString*)checkForNull:(char*)colValue;
 - (NSMutableArray *)executeSelectQuery:(NSString *)query;

 @end

<强> DatabaseOne.m

#import "DatabaseOne.h"
@implementation DatabaseOne
static DatabaseOne *shared = nil;

/***
Create a single GSSQL instance
***/

+(DatabaseOne *)sharedDB;
{
@synchronized([DatabaseOne class])
{
    if (!shared) {
        return [[self alloc] init];
    }
    return shared;
}
return nil;
}

-(id)init
{
shared =  [super init];
return shared;

}

-(id)initWithName:(NSString *)dbname;
{
self = [super init];
if (self) {
    dbName =[[NSString alloc] initWithString:dbname];
    [self copyDatabaseIfNeeded];
}
return self;
}



/***
Create a DB on documents with the name you given dbname;
***/

- (void)createDB:(NSString *)dbname;
{
dbName = [[NSString alloc] initWithString:dbname];
[shared copyDatabaseIfNeeded];
}



/***
Get the DB Path of Database exists in documents folder
***/

- (NSString *) getDBPath {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
return [documentsDir stringByAppendingPathComponent:dbName];
}


/***
Creates and copies the DB from Resources to documents directory
***/

- (void)copyDatabaseIfNeeded {
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSString *dbPath = [self getDBPath];
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:dbName];
BOOL isResourceAvail = [fileManager fileExistsAtPath:defaultDBPath];
if (isResourceAvail == NO) {
    NSLog(@"DB %@ is not exists in Resource to be copied",dbName);
}else
{
    BOOL success = [fileManager fileExistsAtPath:dbPath];
    if(!success) {
        NSLog(@"Copying the DB %@", defaultDBPath);
        success = [fileManager copyItemAtPath:defaultDBPath toPath:dbPath error:&error];

        if (!success)
            NSAssert1(0, @"Failed to copy database: '%@'.", [error localizedDescription]);
    }
}
}


#pragma mark - query execution
/***
Execute the query string(NSString *)
***/

-(BOOL)executeQuery:(NSString *)query;
{
BOOL done = NO;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *dbPath = [self getDBPath];
BOOL success = [fileManager fileExistsAtPath:dbPath];

if(success) {
    int sql_results = sqlite3_open([dbPath UTF8String], &SQLDB);

    const char *sql = [query UTF8String];
    if (sql_results == SQLITE_OK) {

        if(sqlite3_exec(SQLDB, sql, nil, nil, nil) == SQLITE_OK) {
            printf("Good SQL\n");
            done = YES;
        }
        else {
            NSLog(@"Bad SQL: %s -- %d", sql,sql_results);
            //NSLog(@"Bad SQL:%d",sql_results);
        }
    }
    else {
        printf("DB Open FAILED\n");
        NSLog(@"error code %i", sql_results);
    }
    sqlite3_close(SQLDB);
}
else {
    printf("DB not exists in application folder\n");
}
return done;
}


/***
Executes select query and returns array of results
***/


-(NSMutableArray *)executeSelectQuery:(NSString *)query
{
NSMutableArray *results = [[NSMutableArray alloc] init];
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *dbPath = [self getDBPath];
BOOL success = [fileManager fileExistsAtPath:dbPath];

if(success) {
    int sql_results = sqlite3_open([dbPath UTF8String], &SQLDB);
    if (sql_results == SQLITE_OK) {
        const char *sql = [query UTF8String];
        sqlite3_stmt *selectStmt = nil;
        if (sqlite3_prepare_v2(SQLDB, sql, -1, &selectStmt, NULL) == SQLITE_OK) {
            while (sqlite3_step(selectStmt) == SQLITE_ROW) {

                int columnCount = sqlite3_column_count(selectStmt);
                NSMutableDictionary *row = [NSMutableDictionary dictionary];
                for (int i = 0; i < columnCount; i++) {

                    NSString *column_name = [self checkForNull:(char *)sqlite3_column_name(selectStmt, i)];
                    NSString *column_value = [self checkForNull:(char *)sqlite3_column_text(selectStmt, i)];

                    [row setValue:column_value forKey:column_name];
                }
                [results addObject:row];
            }
        }
        sqlite3_reset(selectStmt);
    }
    sqlite3_close(SQLDB);
}
else {
    printf("DB not exists in application folder\n");
}
return results;
}

/***
Checks for a NULL value
***/

- (NSString*)checkForNull:(char*)colValue {

NSString *returnValue = @"something";

if(colValue) {
    returnValue = [NSString stringWithUTF8String:colValue];
}
else {
    returnValue = @"nil";
}
return(returnValue);
}


@end

现在模态数据

<强> Register.h

#import <Foundation/Foundation.h>

@interface Register : NSObject


@property (nonatomic,retain) NSString *strFirstName;
@property (nonatomic,retain) NSString *strLastName;
@property (nonatomic,retain) NSString *strEmailId;
@property (nonatomic,retain) NSString *strPassword;
@property (nonatomic,retain) NSString *strMobileNo;
@property (nonatomic,retain) NSString *strMilliSeconds;
@property (nonatomic,retain) NSString *IsRegister;

-(id)init;

@end

<强> Register.m

#import "Register.h"

@implementation Register



@synthesize strPassword = _strPassword;
@synthesize strMobileNo = _strMobileNo;
@synthesize strEmailId  = _strEmailId;
@synthesize strFirstName = _strFirstName;
@synthesize strLastName = _strLastName;
@synthesize strMilliSeconds = _strMilliSeconds;
@synthesize IsRegister = _IsRegister;


-(id)init
{
    self = [super init];
    if (self != nil)
    {
        _strFirstName = [[NSString alloc]init];
        _strEmailId = [[NSString alloc]init];
        _strPassword = [[NSString alloc]init];
        _strLastName = [[NSString alloc]init];
        _strMobileNo = [[NSString alloc]init];
        _strMilliSeconds = [[NSString alloc]init];
        _IsRegister = [[NSString alloc]init];
    }
    return self;

}
@end

这里我设置了ViewController(RegisterPage)-DataBase

的中间件

<强> ViewController_DBConnection.h

#import <Foundation/Foundation.h>
#import "Register.h"
#import "DatabaseOne.h"
@interface ViewController_DBConnection : NSObject
+(void)registerDB:(Register *)registerDB;
+(NSMutableArray *)GetRegisterAccount:(NSString *) whereQuery;
+(NSMutableArray *)GetRegisterDetail;
@end

<强> ViewController_DBConnection.m

#import "ViewController_DBConnection.h"

@implementation ViewController_DBConnection

+(void)registerDB:(Register *)registerDB
{
    NSString *query = [[NSString alloc]initWithFormat:@"INSERT into TblReg(Firstname,Lastname,EmailId,Password,Mobileno,Milliseconds)values(\"%@\",\"%@\",\"%@\",\"%@\",\"%@\",\"%@\")",registerDB.strFirstName,registerDB.strLastName,registerDB.strEmailId,registerDB.strPassword,registerDB.strMobileNo,registerDB.strMilliSeconds];
    BOOL Success = [[DatabaseOne sharedDB]executeQuery:query];
    if(Success)
    {
        [[NSNotificationCenter defaultCenter]postNotificationName:@"Registration Success" object:nil];
    }

}

+(void)update:(Register *)registerDB
{
   NSString *query = [[NSString alloc]initWithFormat:@"update TblReg Set Firstname = '%@',Lastname = '%@',EmailId = '%@' ,Password = '%@',Mobileno = '%@' WHERE Milliseconds = '%@'",registerDB.strFirstName,registerDB.strLastName,registerDB.strEmailId,registerDB.strPassword,registerDB.strMobileNo,registerDB.strMilliSeconds];
   BOOL Success = [[DatabaseOne sharedDB]executeQuery:query];
   if(Success)
   {
     [[NSNotificationCenter defaultCenter]postNotificationName:@"Updation Success" object:nil];
   }
}

+(NSMutableArray *)GetRegisterAccount:(NSString *) whereQuery
{
    NSString *query=[[NSString alloc]initWithFormat:@"select * from TblReg WHERE %@;", whereQuery];
    NSMutableArray *arrayData = [[DatabaseOne sharedDB]executeSelectQuery:query];
    return arrayData;
}

+(NSMutableArray *)GetRegisterDetail
{
    NSString *query=[[NSString alloc]initWithFormat:@"select * from Register"];
    NSMutableArray *arrayData = [[DatabaseOne sharedDB]executeSelectQuery:query];
    return arrayData;
}

@end

现在我的注册视图控制器

<强> ViewController.h

#import <UIKit/UIKit.h>
#import "DatabaseOne.h"
#import "ViewController_DBConnection.h"
#import "Register.h"

@interface ViewController : UIViewController<UITextFieldDelegate,UITextViewDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>{
    Register *registerDB;
}
@property (strong, nonatomic) IBOutlet UITextField *firstNameTxtFld;
@property (strong, nonatomic) IBOutlet UITextField *lastNameTextField;
@property (strong, nonatomic) IBOutlet UIImageView *imageViewData;
@property (strong, nonatomic) IBOutlet UITextField *emaiIdTextField;
@property (strong, nonatomic) IBOutlet UITextField *passwordTextField;
@property (strong, nonatomic) IBOutlet UITextField *ConfirmPasswordtextField;
@property (strong, nonatomic) IBOutlet UITextField *mobilenoTextField;
- (IBAction)actionSave:(id)sender;
@end

<强> ViewController.m

#import "ViewController.h"

@interface ViewController (){
    CGFloat animatedDistance;
    NSMutableArray *arrayDBGetData;
}

@end
@implementation ViewController
@synthesize firstNameTxtFld,lastNameTextField,emaiIdTextField,passwordTextField,ConfirmPasswordtextField,mobilenoTextField;

static const CGFloat KEYBOARD_ANIMATION_DURATION = 0.3;
static const CGFloat MINIMUM_SCROLL_FRACTION = 0.2;
static const CGFloat MAXIMUM_SCROLL_FRACTION = 0.8;
static const CGFloat PORTRAIT_KEYBOARD_HEIGHT = 216;

- (void)viewDidLoad {
   [super viewDidLoad];
   // Do any additional setup after loading the view, typically from a nib.

    [[DatabaseOne sharedDB] createDB:@"LoginRegistration.sqlite"];
    arrayDBGetData = [[NSMutableArray alloc]init];
    registerDB = [[Register alloc]init];
}


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


//pragma mark - UITextField Dlelgate method
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
      if (![textField isEqual:firstNameTxtFld])  {
        CGRect textViewRect = [self.view.window convertRect:textField.bounds fromView:textField];
        CGRect viewRect = [self.view.window convertRect:self.view.bounds fromView:self.view];
        CGFloat midline = textViewRect.origin.y + 0.5 * textViewRect.size.height;
        CGFloat numerator = midline - viewRect.origin.y - MINIMUM_SCROLL_FRACTION * viewRect.size.height;
        CGFloat denominator =   (MAXIMUM_SCROLL_FRACTION - MINIMUM_SCROLL_FRACTION) * viewRect.size.height;
        CGFloat heightFraction = numerator / denominator;
        if (heightFraction < 0.0)
        {
            heightFraction = 0.0;
        }
        else if (heightFraction > 1.0)
        {
            heightFraction = 1.0;
        }
        animatedDistance = floor(PORTRAIT_KEYBOARD_HEIGHT * heightFraction);
        CGRect viewFrame = self.view.frame;
        viewFrame.origin.y -= animatedDistance;
        [UIView beginAnimations:nil context:NULL];
        [UIView setAnimationBeginsFromCurrentState:YES];
        [UIView setAnimationDuration:KEYBOARD_ANIMATION_DURATION];
        [self.view setFrame:viewFrame];
        [UIView commitAnimations];
    }
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    return YES;
}

- (void)textFieldDidEndEditing:(UITextField *)textField {
    CGRect viewFrame = self.view.frame;
    viewFrame.origin.y += animatedDistance;
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationBeginsFromCurrentState:YES];
    [UIView setAnimationDuration:KEYBOARD_ANIMATION_DURATION];
    [self.view setFrame:viewFrame];
    [UIView commitAnimations];
}

- (IBAction)actionSave:(id)sender{

    registerDB.strFirstName = firstNameTxtFld.text;
    registerDB.strLastName = lastNameTextField.text;
    registerDB.strEmailId = emaiIdTextField.text;
    registerDB.strPassword = passwordTextField.text;
    registerDB.strMobileNo = mobilenoTextField.text;

    [self getMilliSeconds];

    arrayDBGetData = [ViewController_DBConnection GetRegisterAccount:[NSString stringWithFormat:@"EmailId = \"%@\"",registerDB.strEmailId]];

    if([firstNameTxtFld.text length]==0||[lastNameTextField.text length]==0 || [emaiIdTextField.text length]==0 || [ConfirmPasswordtextField.text length] ==0 || [mobilenoTextField.text length]==0){
        [self showAlertController:@"Error!" passMessage:@"Please Enter All Fields"];
    }
    else if([self emailValidation:registerDB.strEmailId] == FALSE){
        [self showAlertController:@"Error!" passMessage:@"Please Enter Valid Email Address"];
    }
    else if(![passwordTextField.text isEqualToString:ConfirmPasswordtextField.text]){
        [self showAlertController:@"Error!" passMessage:@"Please Enter matching password"];
    }
    else if([self checkNumeric:registerDB.strMobileNo] == FALSE){
        [self showAlertController:@"Error!" passMessage:@"Please Enter Valid Mobile No"];
    }
    else if([arrayDBGetData count]!=0){
        [self showAlertController:@"Warning !" passMessage:@"Already user have this Email Address.Try New?"];
    }
    else{
        [[NSNotificationCenter defaultCenter] removeObserver:self name:@"Registration Success" object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(registrationSuccess:)
                                                     name:@"Registration Success"
                                                   object:nil];
        [ViewController_DBConnection registerDB:registerDB];
    }


}

//For Checking mail with - example@gmail.com
-(BOOL)checkValidEmail:(NSString *)checkString{
    BOOL stricterFilter = NO;
    NSString *stricterFilterString = @"^[A-Z0-9a-z\\._%+-]+@([A-Za-z0-9-]+\\.)+[A-Za-z]{2,4}$";
    NSString *laxString = @"^.+@([A-Za-z0-9-]+\\.)+[A-Za-z]{2}[A-Za-z]*$";
    NSString *emailRegex = stricterFilter ? stricterFilterString : laxString;
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailTest evaluateWithObject:checkString];
}

//For Checking mail with - ex@m.in
- (BOOL)emailValidation:(NSString *)email {
    NSString *emailRegEx =
    @"(?:[a-z0-9!#$%\\&'*+/=?\\^_`{|}~-]+(?:\\.[a-z0-9!#$%\\&'*+/=?\\^_`{|}"
    @"~-]+)*|\"(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\"
    @"x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*\")@(?:(?:[a-z0-9](?:[a-"
    @"z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\\[(?:(?:25[0-5"
    @"]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-"
    @"9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21"
    @"-\\x5a\\x53-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])+)\\])";

    NSPredicate *regExPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegEx];
    BOOL myStringMatchesRegEx = [regExPredicate evaluateWithObject:[email lowercaseString]];
    return myStringMatchesRegEx;
}

//For checking Mobile No
- (BOOL)checkNumeric:(NSString *)textvalue {
    NSCharacterSet *nonNumberSet = [[NSCharacterSet characterSetWithRange:NSMakeRange('0',10)] invertedSet];
    NSString *trimmed = [textvalue stringByTrimmingCharactersInSet:[NSCharacterSet symbolCharacterSet]];
    BOOL isNumeric = trimmed.length > 0 && [trimmed rangeOfCharacterFromSet:nonNumberSet].location == NSNotFound;
    return isNumeric;
}


-(void)getMilliSeconds{
    NSDate *now = [[NSDate alloc] init];
    NSDateFormatter *datetimeFormatter =[[NSDateFormatter alloc]init];
    [datetimeFormatter setDateFormat:@"ddMMyyyyHHmmssSS"];
    registerDB.strMilliSeconds=[datetimeFormatter stringFromDate:now];
}

-(void)showAlertController:(NSString *)title passMessage:(NSString *)message{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction* ok = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:nil];
    [alert addAction:ok];
    [self presentViewController:alert animated:YES completion:nil];
}

-(void)registrationSuccess:(NSNotification *)notification
{
    if([[notification name] isEqualToString:@"Registration Success"]){
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Success !" message:@"Registered Successfully" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"Ok" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action){
            [self.navigationController popToRootViewControllerAnimated:YES];
        }];
        [alert addAction:okAction];
        [self presentViewController:alert animated:YES completion:nil];
    }
}

@end

现在最后,一旦我成功注册,我会检查登录屏幕。

<强> RootViewController.h

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

@interface RootViewController : UIViewController<UITextFieldDelegate>
@property (strong, nonatomic) IBOutlet UITextField *usernameTextField;
@property (strong, nonatomic) IBOutlet UITextField *passwordTextField;
- (IBAction)actionLogin:(id)sender;
@end

<强> RootViewController.m

#import“RootViewController.h”

@interface RootViewController ()
{
    NSMutableArray *arrayGetDBData;
    CGFloat animatedDistance;
}

@end

@implementation RootViewController

@synthesize usernameTextField,passwordTextField;

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [[DatabaseOne sharedDB] createDB:@"LoginRegistration.sqlite"];
    arrayGetDBData = [[NSMutableArray alloc]init];
}

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



- (IBAction)actionLogin:(id)sender {

    //@"Error !" message:@"Username or Password is not correct"
    if([usernameTextField.text length]==0||[passwordTextField.text length]==0){
        [self showAlertController:@"Error!" passMessage:@"Please Enter the missing Fields"];
    }
    else{
        arrayGetDBData = [ViewController_DBConnection GetRegisterAccount:[NSString stringWithFormat:@"Emailid = \"%@\"",usernameTextField.text]];
        if(arrayGetDBData.count==0){
            [self showAlertController:@"Error!" passMessage:@"Username is not correct"];
        }
        else if(![passwordTextField.text isEqualToString:[[arrayGetDBData objectAtIndex:0]valueForKey:@"Password"]])
        {
         [self showAlertController:@"Error!" passMessage:@"Password is not correct"];
        }else{
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Success" message:@"Successfully Logged" preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"Ok" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action){

            }];
            [alert addAction:okAction];
            [self presentViewController:alert animated:YES completion:nil];
        }
    }
}


-(void)showAlertController:(NSString *)title passMessage:(NSString *)message{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction* ok = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:nil];
    [alert addAction:ok];
    [self presentViewController:alert animated:YES completion:nil];
}


#pragma mark - UITextField Delegate Methods

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}

static const CGFloat KEYBOARD_ANIMATION_DURATION = 0.3;
static const CGFloat MINIMUM_SCROLL_FRACTION = 0.3;
static const CGFloat MAXIMUM_SCROLL_FRACTION = 0.8;
static const CGFloat PORTRAIT_KEYBOARD_HEIGHT = 216;

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    CGRect textFieldRect = [self.view.window convertRect:textField.bounds fromView:textField];
    CGRect viewRect = [self.view.window convertRect:self.view.bounds fromView:self.view];
    CGFloat midline = textFieldRect.origin.y + 0.5 * textFieldRect.size.height;
    CGFloat numerator = midline - viewRect.origin.y - MINIMUM_SCROLL_FRACTION * viewRect.size.height;
    CGFloat denominator = (MAXIMUM_SCROLL_FRACTION - MINIMUM_SCROLL_FRACTION) * viewRect.size.height;
    CGFloat heightFraction = numerator / denominator;
    if (heightFraction < 0.0)
        heightFraction = 0.0;
    else if (heightFraction > 1.0)
        heightFraction = 1.0;
    animatedDistance = floor(PORTRAIT_KEYBOARD_HEIGHT * heightFraction);
    CGRect viewFrame = self.view.frame;
    viewFrame.origin.y -= animatedDistance;
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationBeginsFromCurrentState:YES];
    [UIView setAnimationDuration:KEYBOARD_ANIMATION_DURATION];
    [self.view setFrame:viewFrame];
}

- (void)textFieldDidEndEditing:(UITextField *)textField
{
    CGRect viewFrame = self.view.frame;
    viewFrame.origin.y += animatedDistance;
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationBeginsFromCurrentState:YES];
    [UIView setAnimationDuration:KEYBOARD_ANIMATION_DURATION];
    [self.view setFrame:viewFrame];
    [UIView commitAnimations];
}
@end

上面我非常清楚地检查了一切。它完美无缺。

答案 3 :(得分:0)

以下是我在表格视图中更新和删除行的答案

**DatabaseOne.h**

 #import <Foundation/Foundation.h>
 #import <sqlite3.h>
 @interface DatabaseOne : NSObject{
 sqlite3 *SQLDB;
 NSString *dbName;
 }

 +(DatabaseOne *)sharedDB;

 -(id)init;
 - (id)initWithName:(NSString *)dbname;
 - (void)createDB:(NSString *)dbname;
 - (NSString *)getDBPath;
 - (void)copyDatabaseIfNeeded;
 - (BOOL)executeQuery:(NSString *)query;
 - (NSString*)checkForNull:(char*)colValue;
 - (NSMutableArray *)executeSelectQuery:(NSString *)query;

 @end

<强> DatabaseOne.m

#import "DatabaseOne.h"
@implementation DatabaseOne
static DatabaseOne *shared = nil;

/***
Create a single GSSQL instance
***/

+(DatabaseOne *)sharedDB;
{
@synchronized([DatabaseOne class])
{
    if (!shared) {
        return [[self alloc] init];
    }
    return shared;
}
return nil;
}

-(id)init
{
shared =  [super init];
return shared;

}

-(id)initWithName:(NSString *)dbname;
{
self = [super init];
if (self) {
    dbName =[[NSString alloc] initWithString:dbname];
    [self copyDatabaseIfNeeded];
}
return self;
}



/***
Create a DB on documents with the name you given dbname;
***/

- (void)createDB:(NSString *)dbname;
{
dbName = [[NSString alloc] initWithString:dbname];
[shared copyDatabaseIfNeeded];
}



/***
Get the DB Path of Database exists in documents folder
***/

- (NSString *) getDBPath {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
return [documentsDir stringByAppendingPathComponent:dbName];
}


/***
Creates and copies the DB from Resources to documents directory
***/

- (void)copyDatabaseIfNeeded {
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSString *dbPath = [self getDBPath];
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:dbName];
BOOL isResourceAvail = [fileManager fileExistsAtPath:defaultDBPath];
if (isResourceAvail == NO) {
    NSLog(@"DB %@ is not exists in Resource to be copied",dbName);
}else
{
    BOOL success = [fileManager fileExistsAtPath:dbPath];
    if(!success) {
        NSLog(@"Copying the DB %@", defaultDBPath);
        success = [fileManager copyItemAtPath:defaultDBPath toPath:dbPath error:&error];

        if (!success)
            NSAssert1(0, @"Failed to copy database: '%@'.", [error localizedDescription]);
    }
}
}


#pragma mark - query execution
/***
Execute the query string(NSString *)
***/

-(BOOL)executeQuery:(NSString *)query;
{
BOOL done = NO;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *dbPath = [self getDBPath];
BOOL success = [fileManager fileExistsAtPath:dbPath];

if(success) {
    int sql_results = sqlite3_open([dbPath UTF8String], &SQLDB);

    const char *sql = [query UTF8String];
    if (sql_results == SQLITE_OK) {

        if(sqlite3_exec(SQLDB, sql, nil, nil, nil) == SQLITE_OK) {
            printf("Good SQL\n");
            done = YES;
        }
        else {
            NSLog(@"Bad SQL: %s -- %d", sql,sql_results);
            //NSLog(@"Bad SQL:%d",sql_results);
        }
    }
    else {
        printf("DB Open FAILED\n");
        NSLog(@"error code %i", sql_results);
    }
    sqlite3_close(SQLDB);
}
else {
    printf("DB not exists in application folder\n");
}
return done;
}


/***
Executes select query and returns array of results
***/


-(NSMutableArray *)executeSelectQuery:(NSString *)query
{
NSMutableArray *results = [[NSMutableArray alloc] init];
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *dbPath = [self getDBPath];
BOOL success = [fileManager fileExistsAtPath:dbPath];

if(success) {
    int sql_results = sqlite3_open([dbPath UTF8String], &SQLDB);
    if (sql_results == SQLITE_OK) {
        const char *sql = [query UTF8String];
        sqlite3_stmt *selectStmt = nil;
        if (sqlite3_prepare_v2(SQLDB, sql, -1, &selectStmt, NULL) == SQLITE_OK) {
            while (sqlite3_step(selectStmt) == SQLITE_ROW) {

                int columnCount = sqlite3_column_count(selectStmt);
                NSMutableDictionary *row = [NSMutableDictionary dictionary];
                for (int i = 0; i < columnCount; i++) {

                    NSString *column_name = [self checkForNull:(char *)sqlite3_column_name(selectStmt, i)];
                    NSString *column_value = [self checkForNull:(char *)sqlite3_column_text(selectStmt, i)];

                    [row setValue:column_value forKey:column_name];
                }
                [results addObject:row];
            }
        }
        sqlite3_reset(selectStmt);
    }
    sqlite3_close(SQLDB);
}
else {
    printf("DB not exists in application folder\n");
}
return results;
}

/***
Checks for a NULL value
***/

- (NSString*)checkForNull:(char*)colValue {

NSString *returnValue = @"something";

if(colValue) {
    returnValue = [NSString stringWithUTF8String:colValue];
}
else {
    returnValue = @"nil";
}
return(returnValue);
}


@end

现在模态数据

<强> Register.h

#import <Foundation/Foundation.h>

@interface Register : NSObject


@property (nonatomic,retain) NSString *strFirstName;
@property (nonatomic,retain) NSString *strLastName;
@property (nonatomic,retain) NSString *strEmailId;
@property (nonatomic,retain) NSString *strPassword;
@property (nonatomic,retain) NSString *strMobileNo;
@property (nonatomic,retain) NSString *strMilliSeconds;
@property (nonatomic,retain) NSString *IsRegister;

-(id)init;

@end

<强> Register.m

#import "Register.h"

@implementation Register



@synthesize strPassword = _strPassword;
@synthesize strMobileNo = _strMobileNo;
@synthesize strEmailId  = _strEmailId;
@synthesize strFirstName = _strFirstName;
@synthesize strLastName = _strLastName;
@synthesize strMilliSeconds = _strMilliSeconds;
@synthesize IsRegister = _IsRegister;


-(id)init
{
    self = [super init];
    if (self != nil)
    {
        _strFirstName = [[NSString alloc]init];
        _strEmailId = [[NSString alloc]init];
        _strPassword = [[NSString alloc]init];
        _strLastName = [[NSString alloc]init];
        _strMobileNo = [[NSString alloc]init];
        _strMilliSeconds = [[NSString alloc]init];
        _IsRegister = [[NSString alloc]init];
    }
    return self;

}
@end

这里我设置了ViewController(RegisterPage)-DataBase

的中间件

<强> ViewController_DBConnection.h

#import <Foundation/Foundation.h>
#import "Register.h"
#import "DatabaseOne.h"
@interface ViewController_DBConnection : NSObject
+(void)registerDB:(Register *)registerDB;
+(void)update:(Register *)registerDB;
+(void)delete:(Register *)registerDB;
+(NSMutableArray *)GetRegisterAccount:(NSString *) whereQuery;
+(NSMutableArray *)GetRegisterDetail;
@end

<强> ViewController_DBConnection.m

#import "ViewController_DBConnection.h"

@implementation ViewController_DBConnection

+(void)registerDB:(Register *)registerDB
{
    NSString *query = [[NSString alloc]initWithFormat:@"INSERT into TblReg(Firstname,Lastname,EmailId,Password,Mobileno,Milliseconds)values(\"%@\",\"%@\",\"%@\",\"%@\",\"%@\",\"%@\")",registerDB.strFirstName,registerDB.strLastName,registerDB.strEmailId,registerDB.strPassword,registerDB.strMobileNo,registerDB.strMilliSeconds];
    BOOL Success = [[DatabaseOne sharedDB]executeQuery:query];
    if(Success)
    {
        [[NSNotificationCenter defaultCenter]postNotificationName:@"Registration Success" object:nil];
    }

}

+(void)update:(Register *)registerDB
{
   NSString *query = [[NSString alloc]initWithFormat:@"update TblReg Set Firstname = '%@',Lastname = '%@',EmailId = '%@' ,Password = '%@',Mobileno = '%@' WHERE Milliseconds = '%@'",registerDB.strFirstName,registerDB.strLastName,registerDB.strEmailId,registerDB.strPassword,registerDB.strMobileNo,registerDB.strMilliSeconds];
   BOOL Success = [[DatabaseOne sharedDB]executeQuery:query];
   if(Success)
   {
     [[NSNotificationCenter defaultCenter]postNotificationName:@"Updation Success" object:nil];
   }
}

+(void)delete:(Register *)registerDB
{
    NSString *query = [[NSString alloc]initWithFormat:@"DELETE FROM TblReg where Milliseconds = '%@'",registerDB.strMilliSeconds];
    BOOL Success = [[DatabaseOne sharedDB]executeQuery:query];
    if(Success)
    {
       [[NSNotificationCenter defaultCenter]postNotificationName:@"Deletion Success" object:nil];
    }
}

+(NSMutableArray *)GetRegisterAccount:(NSString *) whereQuery
{
    NSString *query=[[NSString alloc]initWithFormat:@"select * from TblReg WHERE %@;", whereQuery];
    NSMutableArray *arrayData = [[DatabaseOne sharedDB]executeSelectQuery:query];
    return arrayData;
}

+(NSMutableArray *)GetRegisterDetail
{
    NSString *query=[[NSString alloc]initWithFormat:@"select * from Register"];
    NSMutableArray *arrayData = [[DatabaseOne sharedDB]executeSelectQuery:query];
    return arrayData;
}

@end

<强> EditViewController.h

#import <UIKit/UIKit.h>
#import "DatabaseOne.h"
#import "ViewController_DBConnection.h"
#import "Register.h"


@interface EditViewController : UIViewController{
    Register *registerDB;
}

@property (strong, nonatomic) IBOutlet UITextField *firstnameTxtFld;
@property (strong, nonatomic) IBOutlet UITextField *lastnameTxtFld;
@property (strong, nonatomic) IBOutlet UITextField *emailidTxtFld;
@property (strong, nonatomic) IBOutlet UITextField *passwordTxtFld;
@property (strong, nonatomic) IBOutlet UITextField *mobilenoTxtFld;

@property (strong, nonatomic) NSString *strMilliSeconds;
@property (strong, nonatomic) NSString *strEmailId;

- (IBAction)actionEdit:(id)sender;
- (IBAction)actionBack:(id)sender;
- (IBAction)actionDeleteRow:(id)sender;

<强> EditViewController.m

#import "EditViewController.h"

@interface EditViewController (){
    NSMutableArray *arrayGetDBData;
    CGFloat animatedDistance;
}

@end

@implementation EditViewController

@synthesize firstnameTxtFld,lastnameTxtFld,emailidTxtFld,passwordTxtFld,mobilenoTxtFld,strMilliSeconds,strEmailId;

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [[DatabaseOne sharedDB] createDB:@"LoginRegistration.sqlite"];
    arrayGetDBData = [[NSMutableArray alloc]init];
    arrayGetDBData = [ViewController_DBConnection GetRegisterAccount:[NSString stringWithFormat:@"EmailId = \"%@\"",strEmailId]];
    registerDB = [[Register alloc]init];

    firstnameTxtFld.text = [[arrayGetDBData objectAtIndex:0]valueForKey:@"Firstname"];
    lastnameTxtFld.text = [[arrayGetDBData objectAtIndex:0]valueForKey:@"Lastname"];
    emailidTxtFld.text = [[arrayGetDBData objectAtIndex:0]valueForKey:@"EmailId"];
    passwordTxtFld.text = [[arrayGetDBData objectAtIndex:0]valueForKey:@"Password"];
    mobilenoTxtFld.text = [[arrayGetDBData objectAtIndex:0]valueForKey:@"Mobileno"];
    registerDB.strMilliSeconds = [[arrayGetDBData objectAtIndex:0]valueForKey:@"Milliseconds"];
}

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

#pragma mark - UITextField Delegate Methods

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}

static const CGFloat KEYBOARD_ANIMATION_DURATION = 0.3;
static const CGFloat MINIMUM_SCROLL_FRACTION = 0.3;
static const CGFloat MAXIMUM_SCROLL_FRACTION = 0.8;
static const CGFloat PORTRAIT_KEYBOARD_HEIGHT = 216;

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    CGRect textFieldRect = [self.view.window convertRect:textField.bounds fromView:textField];
    CGRect viewRect = [self.view.window convertRect:self.view.bounds fromView:self.view];
    CGFloat midline = textFieldRect.origin.y + 0.5 * textFieldRect.size.height;
    CGFloat numerator = midline - viewRect.origin.y - MINIMUM_SCROLL_FRACTION * viewRect.size.height;
    CGFloat denominator = (MAXIMUM_SCROLL_FRACTION - MINIMUM_SCROLL_FRACTION) * viewRect.size.height;
    CGFloat heightFraction = numerator / denominator;
    if (heightFraction < 0.0)
        heightFraction = 0.0;
    else if (heightFraction > 1.0)
        heightFraction = 1.0;
    animatedDistance = floor(PORTRAIT_KEYBOARD_HEIGHT * heightFraction);
    CGRect viewFrame = self.view.frame;
    viewFrame.origin.y -= animatedDistance;
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationBeginsFromCurrentState:YES];
    [UIView setAnimationDuration:KEYBOARD_ANIMATION_DURATION];
    [self.view setFrame:viewFrame];
}

- (void)textFieldDidEndEditing:(UITextField *)textField
{
    CGRect viewFrame = self.view.frame;
    viewFrame.origin.y += animatedDistance;
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationBeginsFromCurrentState:YES];
    [UIView setAnimationDuration:KEYBOARD_ANIMATION_DURATION];
    [self.view setFrame:viewFrame];
    [UIView commitAnimations];
}
//For Checking mail with - ex@m.in
- (BOOL)emailValidation:(NSString *)email {
    NSString *emailRegEx =
    @"(?:[a-z0-9!#$%\\&'*+/=?\\^_`{|}~-]+(?:\\.[a-z0-9!#$%\\&'*+/=?\\^_`{|}"
    @"~-]+)*|\"(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\"
    @"x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*\")@(?:(?:[a-z0-9](?:[a-"
    @"z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\\[(?:(?:25[0-5"
    @"]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-"
    @"9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21"
    @"-\\x5a\\x53-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])+)\\])";

    NSPredicate *regExPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegEx];
    BOOL myStringMatchesRegEx = [regExPredicate evaluateWithObject:[email lowercaseString]];
    return myStringMatchesRegEx;
}


-(BOOL)isNumeric:(NSString*)inputString{
    NSCharacterSet *charcter =[[NSCharacterSet characterSetWithCharactersInString:@"0123456789"] invertedSet];
    NSString *filtered;
    filtered = [[inputString componentsSeparatedByCharactersInSet:charcter] componentsJoinedByString:@""];
    return [inputString isEqualToString:filtered];
}


- (BOOL)checkNumeric:(NSString *)textvalue {
    NSCharacterSet *nonNumberSet = [[NSCharacterSet characterSetWithRange:NSMakeRange('0',10)] invertedSet];
    NSString *trimmed = [textvalue stringByTrimmingCharactersInSet:[NSCharacterSet symbolCharacterSet]];
    BOOL isNumeric = trimmed.length > 0 && [trimmed rangeOfCharacterFromSet:nonNumberSet].location == NSNotFound;
    return isNumeric;
}


-(void)getMilliSeconds{
    NSDate *now = [[NSDate alloc] init];
    NSDateFormatter *datetimeFormatter =[[NSDateFormatter alloc]init];
    [datetimeFormatter setDateFormat:@"ddMMyyyyHHmmssSS"];
    registerDB.strMilliSeconds=[datetimeFormatter stringFromDate:now];
}

-(void)showAlertController:(NSString *)title passMessage:(NSString *)message{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction* ok = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:nil];
    [alert addAction:ok];
    [self presentViewController:alert animated:YES completion:nil];
}

- (IBAction)actionEdit:(id)sender {
    registerDB.strFirstName = firstnameTxtFld.text;
    registerDB.strLastName = lastnameTxtFld.text;
    registerDB.strEmailId = emailidTxtFld.text;
    registerDB.strPassword = passwordTxtFld.text;
    registerDB.strMobileNo = mobilenoTxtFld.text;

    arrayGetDBData = [ViewController_DBConnection GetRegisterAccount:[NSString stringWithFormat:@"EmailId = \"%@\"",registerDB.strEmailId]];

    if([firstnameTxtFld.text length]==0 || [lastnameTxtFld.text length]==0 || [emailidTxtFld.text length]==0 ||  [mobilenoTxtFld.text length]==0 ||  [passwordTxtFld.text length]==0){
        [self showAlertController:@"Error!" passMessage:@"Please Enter All Fields"];
    }
    else if([self emailValidation:registerDB.strEmailId] == FALSE){
        [self showAlertController:@"Error!" passMessage:@"Please Enter Valid Email Address"];
    }
    else if([self checkNumeric:registerDB.strMobileNo] == FALSE){
        [self showAlertController:@"Error!" passMessage:@"Please Enter Valid Mobile No"];
    }
    else if([arrayGetDBData count]!=0){
        [self showAlertController:@"Warning !" passMessage:@"Already user have this Email Address.Try New?"];
    }
    else{
        [[NSNotificationCenter defaultCenter] removeObserver:self name:@"Updation Success" object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(updationSuccess:)
                                                     name:@"Updation Success"
                                                   object:nil];
        [ViewController_DBConnection update:registerDB];
    }
}

- (IBAction)actionDeleteRow:(id)sender
{
    registerDB.strFirstName = firstnameTxtFld.text;
    registerDB.strLastName = lastnameTxtFld.text;
    registerDB.strEmailId = emailidTxtFld.text;
    registerDB.strPassword = passwordTxtFld.text;
    registerDB.strMobileNo = mobilenoTxtFld.text;

    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"Deletion Success" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(deletionSuccess:)
                                                 name:@"Deletion Success"
                                               object:nil];
    [ViewController_DBConnection delete:registerDB];
}
- (IBAction)actionBack:(id)sender {
    [self.navigationController popToRootViewControllerAnimated:YES];
}

-(void)updationSuccess:(NSNotification *)notification
{
    if([[notification name] isEqualToString:@"Updation Success"])
    {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Success !" message:@"Updated Successfully" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"Ok" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action){
            [self.navigationController popToRootViewControllerAnimated:YES];
        }];
        [alert addAction:okAction];
        [self presentViewController:alert animated:YES completion:nil];
    }
}

-(void)deletionSuccess:(NSNotification *)notification
{
    if([[notification name] isEqualToString:@"Deletion Success"])
    {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Success !" message:@"Deleted Successfully" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"Ok" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action){
            [self.navigationController popToRootViewControllerAnimated:YES];
        }];
        [alert addAction:okAction];
        [self presentViewController:alert animated:YES completion:nil];
    }
}
@end