iOS Sqlite 数据库初学者指南
Posted
技术标签:
【中文标题】iOS Sqlite 数据库初学者指南【英文标题】:iOS Sqlite Database guide for beginner 【发布时间】:2016-12-26 11:35:26 【问题描述】:我也是 ios 技术的初学者。根据我的标题,这个问题可能对每个新开发人员都有帮助。
所以欢迎大家编辑我的答案并纠正我或提出你自己的答案来提高我们的知识。
在下面的例子中我正在考虑
1) 一个表名为“Student” 2) 以下是字段名称 - 名字 - 姓 - 地址 - 出生日期
在这里我们可以对表中的记录进行“添加”、“更新”、“删除”和“获取”记录等操作操作。
更新:
根据其他用户的回答,我们也可以通过CoreData
进行管理。但是CoreData
比SQLite
更快更容易吗?如果数据很复杂,那么CoreData
如何管理?
【问题讨论】:
我认为这类问题已经有很多答案了。有很多教程包含使用 SQLite、Core Data、Realm 等管理数据库的示例代码。如果你在谷歌上搜索,你可以很容易地找到所有这些东西。尝试这些东西,如果您对实现中的任何内容仍然不了解,那么您应该在这里提出相关问题。 【参考方案1】:首先我们需要创建 SQLite 数据库和表。我在想有很多方法可以创建数据库和表,但我使用的是最充分的方法
1) 安装 Firefox 并安装附加组件 https://addons.mozilla.org/en-US/firefox/addon/sqlite-manager/
2) 创建数据库 - 继续 Firefox -> 工具 -> SQLite 管理器 - 左上角选择 3rd -> New Database OR 在菜单栏上,选择“Database” -> New Database - 将数据库名称命名为“student”并在您的项目中保存正确的位置。
3) 创建表 - 左侧菜单 -> 选择“表格(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 数据库。
【讨论】:
【参考方案2】:如果你是iOS技术的初学者,想学习本地存储管理,那么我建议你去CoreData
:
Manage Local storage using Core Data
因为使用核心数据,您可以以对象和类的形式与本地数据库进行交互。
【讨论】:
"CoreData" 是的,我正在学习,但你能告诉我哪一个是简单且足够的 SQLite 或 Coredata? 我必须建议您使用coredata,如果您想知道使用它的优点,请参考:***.com/questions/6377274/…【参考方案3】:根据您的问题,他们中的大多数人说
Coredta is better than SQLite
当你通过 Adds-on 工具使用 SQLite 时,我们需要做以下事情。我解释清楚。
我的数据库名称是 - LoginRegistration.sqlite
我的数据库表名是 - TblReg
我有登录屏幕。在其中我有用户名和密码字段。在下面我有登录和注册按钮。
当您单击注册按钮时,它会转到注册页面视图控制器,我们必须先在其中注册,然后我们必须保存数据,然后将数据插入我们的 SQLite db。
为了实现 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
上面我检查得很清楚。它工作得很好。
【讨论】:
很好的解释代码感谢我和其他人更清楚【参考方案4】:这是我从表格视图中更新和删除行的答案
**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
【讨论】:
以上是关于iOS Sqlite 数据库初学者指南的主要内容,如果未能解决你的问题,请参考以下文章
ios sqlite fts 扩展“没有这样的模块 fts4”错误