IOS dev: Just need help in exc_bad_access error - ios

Help, my app is showing thread 1 error exc_bad_access(code=1, address=0x2000001) on the last curly brace of my PlayViewController.
Note: this happen when I click the continue button on my GuessViewController. The continue button calls the the PlayViewController.
What i already did:
enabled ZOMBIE
close db
my GuessViewController:
#import "GuessViewController.h"
#import "PlayViewController.h"
#import "ViewController.h"
#interface GuessViewController ()
#end
#implementation GuessViewController
#synthesize userInput = _userInput;
#synthesize gword;
#synthesize gletter;
int score = 0;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
_userInput.delegate = self;
self.scoreLabel.text = [NSString stringWithFormat:#"%d", score];
// Do any additional setup after loading the view.
}
-(void)touchesBegan:(NSSet*)touches withEvent: (UIEvent *) event{
[_userInput resignFirstResponder];
}
-(BOOL)textFieldShouldReturn: (UITextField*)textField {
if(textField){
[textField resignFirstResponder];
}
return NO;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)checkAnswer:(id)sender {
NSLog(#"%#", gword);
NSLog(#"%#", gletter);
NSString *temp = self.userInput.text;
unichar temp2 = [temp characterAtIndex: 0];
NSString *userletter= [NSString stringWithFormat:#"%C", temp2];
NSString *message1 = #"The word is ";
NSString *message2= [NSString stringWithFormat:#"%#", gword];
NSString *fm = [message1 stringByAppendingString:message2];
if([userletter isEqualToString:gletter]){
UIAlertView *checkAlert = [[UIAlertView alloc] initWithTitle:#"Got it Right" message:fm delegate:self cancelButtonTitle:#"Continue" otherButtonTitles:#"Back to Main Menu", nil];
score++;
self.scoreLabel.text = [NSString stringWithFormat:#"%d", score];
[checkAlert show];
}else{
UIAlertView *checkAlert = [[UIAlertView alloc] initWithTitle:#"Wrong" message:fm delegate:self cancelButtonTitle:#"Continue" otherButtonTitles:#"Back to Main Menu", nil];
[checkAlert show];
}
}
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
if(buttonIndex ==0){
PlayViewController *playViewController = [self.storyboard instantiateViewControllerWithIdentifier:#"Play"];
[self presentViewController:playViewController animated:YES completion: Nil];
} else {
ViewController *viewController = [self.storyboard instantiateViewControllerWithIdentifier:#"Main"];
[self presentViewController:viewController animated:YES completion: Nil];
}
}
#end
My PlayViewController:
#import "PlayViewController.h"
#import "GuessViewController.h"
#import <sqlite3.h>
#import "Word.h"
#interface PlayViewController ()
#end
#implementation PlayViewController
#synthesize thewords;
NSString *word;
NSTimer *myTimer;
int randomIndex;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[self wordList];
[super viewDidLoad];
// Do any additional setup after loading the view.
self.listChar.text = #" ";
int r = (arc4random()%[self.thewords count]);
word = [self.thewords objectAtIndex:r];
NSLog(#"%#", word);
randomIndex = (arc4random()%word.length);
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
/*
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
- (IBAction)startGame:(id)sender {
myTimer = [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:#selector(listLetter:) userInfo:nil repeats:YES];
}
- (void)listLetter:(NSTimer *)timer
{
static int i = 0;
unichar letter;
if(randomIndex == i){
letter = ' ';
} else {
letter = [word characterAtIndex: i];
}
self.listChar.text = [NSString stringWithFormat:#"%C", letter];
if (++i == word.length) {
[timer invalidate];
i = 0;
GuessViewController *guessViewController = [self.storyboard instantiateViewControllerWithIdentifier:#"Guess"];
//passing some data
guessViewController.word = word;
guessViewController.letter = [NSString stringWithFormat:#"%C", [word characterAtIndex: randomIndex]];
[self presentViewController:guessViewController animated:YES completion: Nil];
}
}
-(NSMutableArray *) wordList {
thewords = [[NSMutableArray alloc] initWithCapacity:26];
#try {
NSFileManager *fileMgr = [NSFileManager defaultManager];
NSString *dbPath = [[[NSBundle mainBundle] resourcePath ]stringByAppendingPathComponent:#"LetterHunter.sqlite"];
BOOL success = [fileMgr fileExistsAtPath:dbPath];
if(!success){
NSLog(#"Cannot locate database file '%#'.", dbPath);
}
if(!(sqlite3_open([dbPath UTF8String], &db) == SQLITE_OK)){
NSLog(#"An error has occured");
}
const char *sql = "SELECT * FROM WordList";
sqlite3_stmt*sqlStatement;
if(sqlite3_prepare_v2(db, sql, -1, &sqlStatement, NULL)!=SQLITE_OK){
NSLog(#"Problem with prepare statement1");
} else {
while(sqlite3_step(sqlStatement) == SQLITE_ROW){
Word *word = [[Word alloc]init];
word.wordfromdb = [NSString stringWithUTF8String:(char*)sqlite3_column_text(sqlStatement, 1)];
[thewords addObject: word.wordfromdb];
}
}
sqlite3_finalize(sqlStatement);
}
#catch (NSException *exception) {
NSLog(#"Problem with prepare statement2");
}
#finally {
sqlite3_close(db);
}
}
#end
As suggested below, I tried doing this instead but still there's the error
while(sqlite3_step(sqlStatement) == SQLITE_ROW){
NSString *temp = #"";
temp = [NSString stringWithUTF8String:(char*)sqlite3_column_text(sqlStatement, 1)];
[thewords addObject: temp;
}

From debug stack, it's a problem about autorelease. And I think the problem maybe in
if(!(sqlite3_open([dbPath UTF8String], &db) == SQLITE_OK)){
I can't find db define. So I think it should be a instance property.
Try this:
DbClass *tempDb = nil;
if(!(sqlite3_open([dbPath UTF8String], &tempDb) == SQLITE_OK)){
self.db = tempDb;

What is wordfromdb? If it is string variable or any other datatype then add directly that into an array...
I think there is not need to create word object here as anyway your are not storing word object in array.
It looks to me an issue with word object. You are crating word object but adding its property only and not entire object.

Related

iOS Sqlite Database guide for beginner

I'm also beginner for iOS technology. And as per my title saying that might be this question will helpful for each new developer.
So welcome to all edit my answer and correct me OR put your own answer to improve our knowledge.
In the below Example I'm considering
1) One table name is “Student”
2) Below are fields name
- First Name
- Last Name
- Address
- Birth Date
Here we can apply manipulate operation such like “Add”, “Update”, “Delete” and “Fetch” record from the table.
UPDATE :
As per other user's answer we also can mange by CoreData too. But CoreData is faster and easier then SQLite ? If data is complex then how can we manage by CoreData?
First we need to create SQLite database and table. I’m thinking there are so many way to create database and table but most sufficient way that I’m using
1) Install Firefox and Install Add-ons
https://addons.mozilla.org/en-US/firefox/addon/sqlite-manager/
2) Create Database
- Go on Firefox -> tools -> SQLite Manager
- Top left corner choose 3rd -> New Database OR On the menu bar, choose “Database” -> New Database
- Give Database name “student” and save right place in your project.
3) Create Table
- Left side menu-> select “Tables(0)” -> Right click - Create Table OR On the menu bar, choose “Table” -> Create Table
- Give Table name “student_info” and save right place in your project.
Belo Are the code for execute manipulate operation.
#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;
And for .m file
#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);
}
Above are .H and .M file that will help you to manage SQLite database.
If you are a beginner to iOS technology and want to learn local storage management then i will suggest you to go with CoreData:
Manage Local storage using Core Data
Because using core data you can interact with local database in a form of object and class.
According to your Question most of them say
Coredta is better than SQLite
When you use SQLite using Adds-on tool we need to do the below things.I explain you clearly.
My DB Name is - LoginRegistration.sqlite
My DB Table Name is - TblReg
I have Login Screen.In that I have username and password field.Below that I have Login and Register Button.
When you click register button it goes to registration page view controller where we have to register first then we have to save the data on insert the data into our SQLite db.
For implementing SQLite,first we must add and import the 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
Now the Modal data are
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
Here I set the intermediate for 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
Now my Register View Controller
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
Now Finally I check the login screen once I registered successfully.
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
Above I checked everything very clearly.It works perfectly.
Here is my answer for updating and deleting the row from the table view
**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
Now the Modal data are
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
Here I set the intermediate for 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 8.3 BLE Device keeps disconnecting after connecting objective-c

I have a Shearwell stick reader, which reads in cattle tags, sheep tags and goat tags via BLE. When connecting the BLE device, the device list shows up in the tableView of the SDLBluetoothConnectViewController then disappears. I am also not able to grab the information from the device using a segue. The bluetooth icon flashes 3 times and does not pair with the device. Can anyone see where my error is i've looked for hours!! thanks in advance!
here is the SDLStickreader.m
// A StickReader is a wrapper for a CBPeripheral that has been discovered using a filter for StickReader UUID.
#import "SDLStickReader.h"
#import "SDLStickReaderManager.h"
#import "SDLStickReaderPrivate.h"
#import "SDLSerialPort.h"
//#import "SDLIdentifier.h"
#interface SDLStickReader () <SerialPortDelegate>
#property (strong, nonatomic) CBPeripheral *peripheral;
#end
#implementation SDLStickReader
static SDLStickReaderManager * _manager;
NSMutableData *_data;
SDLSerialPort *serialPort;
BOOL waitingForConfigInfo = YES;
NSMutableString *configString;
+(SDLStickReaderManager *)manager {
if (nil == _manager) {
_manager = [[SDLStickReaderManager alloc] init];
}
return _manager;
}
+ (instancetype)forPeripheral: (CBPeripheral *)peripheral {
return [[self alloc] initWithPeripheral:peripheral];
}
- (instancetype)initWithPeripheral: (CBPeripheral *)peripheral {
self = [super init];
if (self) {
_detail = #"";
self.peripheral = peripheral;
//peripheral.delegate = self;
__tagReadService = [CBUUID UUIDWithString:SDL_STICKREADER_TAGREAD_UUID];
if (peripheral.state == CBPeripheralStateConnected) {
NSLog(#"periperal is connected");
} else {
NSLog(#"periperal is NOT connected");
}
_data = [[NSMutableData alloc] init];
serialPort = [[SDLSerialPort alloc] initWithPeripheral:peripheral andDelegate:self];
peripheral.delegate = self;
[serialPort open ];
}
return self;
}
-(BOOL)hasPeripheral: (CBPeripheral *)peripheral {
return [self.peripheral isEqual: peripheral];
}
-(NSUUID *)identifier {
return self.peripheral.identifier;
}
-(NSString *)name {
return self.peripheral.name;
}
-(NSString *)description {
return [NSString stringWithFormat: #"Peripheral: %#", self.name];
}
-(NSString *)state {
switch (self.peripheral.state) {
case CBPeripheralStateConnected:
return SDL_STICKREADER_STATE_CONNECTED;
case CBPeripheralStateConnecting:
return SDL_STICKREADER_STATE_CONNECTING;
case CBPeripheralStateDisconnected:
return SDL_STICKREADER_STATE_DISCONNECTED;
}
}
// Every time the peripheral sends new data, it calls the delegate peripheral:didUpdateValueForCharacteristic:error: method. The second argument contains the characteristic that you can read.
- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic: (CBCharacteristic *)characteristic error:(NSError *)error {
if (error) {
NSLog(#"Error");
return;
}
if ([self.characteristics containsObject: characteristic.UUID]) {
NSString *stringFromData = [[NSString alloc] initWithData:characteristic.value encoding:NSUTF8StringEncoding];
// Have we got everything we need?
NSUInteger startOfEom = [stringFromData rangeOfString: SDL_STICKREADER_EOM].location;
if (NSNotFound == startOfEom) {
// it is not the EOM so append the data to what we have so far and wait for more.
[_data appendData: characteristic.value];
} else {
// contains EOM, so remove the
NSString *lastPart = [stringFromData substringToIndex:startOfEom];
NSString *message = [[NSString alloc] initWithData: _data encoding:NSUTF8StringEncoding];
if (nil != lastPart && lastPart.length > 0) {
message = [message stringByAppendingString:lastPart];
}
if (nil != self.listener) {
[self.listener stickReader:self didReadTag:message];
}
[_data setLength:0];
}
}
}
// Method that ensures that the CBCentral knows when a notification state for a given characteristic changes. Track it in order to understand when a characteristic state changes (update app values). You should check if the characteristic notification has stopped. If it has, you should disconnect from it:
- (void)peripheral:(CBPeripheral *)peripheral didUpdateNotificationStateForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error {
if (![self.characteristics containsObject: characteristic.UUID]) {
return;
}
if (characteristic.isNotifying) {
NSLog(#"Notification began ");
} else {
// Notification has stopped
NSLog(#"Notification stopped ");
//[_manager cancelPeripheralConnection:peripheral];
}
}
/////////////////////////////////////////////////////////////////////////////////////
- (void) port: (SDLSerialPort*) serialPort event : (SPEvent) ev error: (NSInteger)err {
if (SP_EVT_OPEN == ev) {
//NSLog(#"serialPortOpened");
configString = [[NSMutableString alloc] init];
[serialPort write: [#"c\r" dataUsingEncoding: NSUTF8StringEncoding]];
} else {
NSLog(#"serialPortClosed");
}
}
- (void) writeComplete: (SDLSerialPort*) serialPort withError: (NSInteger)err {
NSLog(#"writeComplete");
}
- (void) port: (SDLSerialPort*) serialPort receivedData: (NSData*)data {
if (data.length > 0) {
NSCharacterSet *charSet = [NSCharacterSet characterSetWithCharactersInString: #"|()#"];
NSString *str = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
NSLog(#"receivedData: %#", str);
if ([str hasPrefix: #"Shearwell"]) {
_detail = str;
//NSLog(#"updating: %#", str);
[[SDLStickReader manager] addedShearwellStickReader: self];
} else if (NSNotFound != [str rangeOfCharacterFromSet: charSet].location ) {
// Data
if (waitingForConfigInfo) {
[configString appendString:str];
if (NSNotFound != [configString rangeOfString: #"(cS)"].location) {
// got end of config string, parse config.
NSRange found = [configString rangeOfString: #"#18|"];
if (NSNotFound != found.location) {
NSRange getRange = NSMakeRange(found.location + found.length, 1);
NSString *str = [configString substringWithRange: getRange];
self.eidFormat = [str integerValue];
NSLog(#"StickReader format: %d", self.eidFormat);
}
waitingForConfigInfo = NO;
[serialPort write: [#"v\r" dataUsingEncoding: NSUTF8StringEncoding]];
}
} else {
// Users data
[self.listener stickReader:self didReadData: str];
}
} else {
// Tag
if (nil != self.listener) {
[self.listener stickReader:self didReadTag: str];
}
}
}
}
and my SDLBluetoothConnectViewController.m
#import "SDLBluetoothConnectViewController.h"
#import "SDLStickReaderManager.h"
#import "SDLStickReader.h"
#import "SDLViewController.h"
#interface SDLBluetoothConnectViewController () <UITableViewDataSource, UITableViewDelegate, SDLStickReaderManagerListener>
#property (weak, nonatomic) IBOutlet UITableView *stickReaderListView;
#property (strong, nonatomic) IBOutlet UILabel *stickReaderNameLabel;
#property (strong, nonatomic) IBOutlet UILabel *stickReaderDescLabel;
#end
/*
This class starts the process of scanning in the 'viewDidLoad' method by setting the SDLStickReaderManager 'singleton' to self. When the scan button is pressed the SDLStickReaderManager scan is called, and each stick reader found is returned via the listener call. This listener call is used to refresh the table view.
When a user selects a stick reader from the list the StickReader view is started and passed the selected stick reader.
*/
#implementation SDLBluetoothConnectViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
[self.stickReaderListView setDelegate: self];
[self.stickReaderListView setDataSource: self];
[SDLStickReader manager].listener = self;
[self.stickReaderListView reloadData];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)scanButtonPressed:(id)sender {
[SDLStickReader.manager scan];
}
- (IBAction)cancelButtonPressed:(id)sender {
SDLStickReader.manager.listener = nil;
[self dismissViewControllerAnimated:YES completion:nil];
}
-(void)viewWillDisappear:(BOOL)animated {
/*
Every time the view disappears, you should stop the scanning process.
*/
[SDLStickReader.manager stopScan];
}
/////////////////////////////////////////////////////////////////////////////////
/////// Table handling //////////////////////////////////////////////////////////
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
NSArray *stickReaders = SDLStickReader.manager.discoveredStickReaders;
SDLStickReader * stickReader = [stickReaders objectAtIndex: indexPath.row];
[SDLStickReader.manager stopScan];
[self performSegueWithIdentifier:#"deviceInfoSegue" sender:self];
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
NSArray *stickReaders = SDLStickReader.manager.discoveredStickReaders;
return stickReaders.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString * simpleTableIdentifier = #"SimpleTableCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier: simpleTableIdentifier];
if (nil == cell) {
cell = [[UITableViewCell alloc] initWithStyle: UITableViewCellStyleDefault reuseIdentifier: simpleTableIdentifier];
}
NSArray *stickReaders = SDLStickReader.manager.discoveredStickReaders;
SDLStickReader * stickReader = [stickReaders objectAtIndex: indexPath.row];
NSString *desc = [stickReader name];
cell.textLabel.text = desc;
return cell;
}
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([[segue identifier] isEqualToString:#"deviceInfoSegue"]) {
//some additional info here
}
}
////////////////////////////////////////////////////////////////////////////////// /
/// SDLStickReaderManager callbacks ///////////////////////////////////////////////
-(void)stickReader: (SDLStickReader *)stickReader addedToList: (NSArray *)discoveredStickReaders {
//NSLog(#"View StickReaderAdded");
[self.stickReaderListView reloadData];
//[SDLStickReader.manager connect: stickReader];
}
-(void)connectedStickReader: (SDLStickReader *)stickReader {
//NSLog(#"View StickReader connected");
[self.stickReaderListView reloadData];
}
-(void)disconnectedStickReader: (SDLStickReader *)stickReader {
//NSLog(#"View StickReader disconnected");
[self.stickReaderListView reloadData];
}

Stuck in Accessing Contacts from PhoneBook in IOS

I want to access all contacts from phonebook in IOS. I have tried below code
CFErrorRef error = NULL;
ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, &error);
if (addressBook != nil)
{
NSLog(#"Succesful.");
NSArray *allContacts = (__bridge_transfer NSArray *)ABAddressBookCopyArrayOfAllPeople(addressBook);
}
this code is working good and all contacts get stored in "allContacts" array in my demo project but when i put this code in my existing project its returning "nil" record.
Below is my header and implementation files of my existing project in which actually i want to use it.
//.h file
#import <UIKit/UIKit.h>
#import <AddressBook/AddressBook.h>
#import <AddressBookUI/AddressBookUI.h>
#interface TestingViewController : UIViewController
-(IBAction)GetContacts;
-(void)GetPBAccess;
#end
//.m file
#import "TestingViewController.h"
#import <AddressBook/AddressBook.h>
#import <AddressBookUI/AddressBookUI.h>
#interface TestingViewController ()
#end
#implementation TestingViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
[self GetPBAccess];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(void)GetPBAccess
{
ABAddressBookRef addressBook1 = ABAddressBookCreateWithOptions(NULL, NULL);
switch (ABAddressBookGetAuthorizationStatus()) {
case kABAuthorizationStatusNotDetermined:
{
ABAddressBookRequestAccessWithCompletion(addressBook1, ^(bool granted, CFErrorRef error) {
if (granted) {
NSLog(#"Access Granted");
[self GetContacts];
}
else{
NSLog(#"Access Not Granted");
}
});
break;
}
case kABAuthorizationStatusAuthorized:
{
NSLog(#"AUTHORIZATION ALREADY Granted");
[self GetContacts];
break;
}
case kABAuthorizationStatusDenied:
{
NSLog(#"AUTHORIZATION DENIED");
break;
}
default:
break;
}
}
-(IBAction)GetContacts
{
CFErrorRef error = NULL;
ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, &error);
if (addressBook != nil)
{
NSLog(#"Succesful.");
NSArray *allContacts = (__bridge_transfer NSArray *)ABAddressBookCopyArrayOfAllPeople(addressBook);
NSUInteger i = 0;
for (i = 0; i < [allContacts count]; i++)
{
//Person *person = [[Person alloc] init];
ABRecordRef contactPerson = (__bridge ABRecordRef)allContacts[i];
NSString *firstName = (__bridge_transfer NSString *)ABRecordCopyValue(contactPerson, kABPersonFirstNameProperty);
NSString *lastName = (__bridge_transfer NSString *)ABRecordCopyValue(contactPerson, kABPersonLastNameProperty);
NSString *fullName = [NSString stringWithFormat:#"%# %#", firstName, lastName];
// person.firstName = firstName;
// person.lastName = lastName;
// person.fullName = fullName;
//email
ABMultiValueRef emails = ABRecordCopyValue(contactPerson, kABPersonEmailProperty);
// NSUInteger j = 0;
// for (j = 0; j < ABMultiValueGetCount(emails); j++)
// {
// NSString *email = (__bridge_transfer NSString *)ABMultiValueCopyValueAtIndex(emails, j);
// if (j == 0)
// {
// person.homeEmail = email;
// NSLog(#"person.homeEmail = %# ", person.homeEmail);
// }
//
// else if (j==1)
// person.workEmail = email;
// }
//
// [self.tableData addObject:person];
}
}
CFRelease(addressBook);
}
/*
#pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
#end
The problem looks to be because you call
[self GetPBAccess];
[self GetContacts];
directly inline. What you should do is move the GetContacts call into the GetPBAccess so that it's called once you know you have access (and not called if you don't have access).
At the moment it will run before the user has granted access, certainly the first time you try it, and return nothing.

Proper way to implement a login process in iOS apps

When a user run my app for the first time a LoginViewController appears. Once he is logged in, I present a ModalViewController with all the stuff of the app. If the user want to log out, I dismiss the modal view, showing the LoginViewController again.
The problem comes if the user runs the app when is already logged. In the self.window.rootViewController, I set directly the main view of the app (embebed in a UITabBarController), so if the user want to log out, I don't know the way to "dismiss" the view and show the LoginViewController.
SCENARIO:
User no logged yet: LoginViewController -> (Log in) -> UITabBarController -> (Log out) -> LoginViewController.
User already logged: UITabBarController -> (Log out) -> LoginViewController.
I think there must be a simple way to do this, because it is a very normal behavior in an app with a login system, but I haven't found a clean way to do it.
After struggling with this many times, we published an open source library called CLHoppingViewController which handles exactly this kind of scenarios.
So, in your case, you would do something like this to describe the start up flow:
UIViewController *loginViewController;
UIViewController *mainViewController;
if (user_not_logged_in) {
[self hopToViewController:loginViewController then:^{
[self hopToViewController:mainViewController then:nil];
}];
}
else {
[self hopToViewController:mainViewController then:nil];
}
The library can support much more advanced conditional sequences. For example, you can display a splash screen, conditionally show onboarding UX, etc.
There's a short tutorial here.
Try following way :
TabBarController *tabBarController1 = [[TabBarController alloc] init];
self.window.rootViewController = tabBarController1.myTabBarController;
[self.window makeKeyAndVisible];
// if not Logedin
if() {
self.viewController = [[LoginViewController alloc] initWithNibName:#"LoginViewController" bundle:nil];
UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:self.viewController];
[self.tabBarController1 presentModalViewController:navController animated:NO];
}
After Login, dismiss LoginViewController. Again while logout present LoginViewController modally on tabBarViewController as above.
I did this:
App Delegate:
if() //signed in
{
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
TabBarController *tabBarController1 = [[TabBarController alloc] init];
self.window.rootViewController = tabBarController1.myTabBarController;
[self.window makeKeyAndVisible];
}
else //signed out
{
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
self.viewController = [[SigninTabBarTemplateViewController alloc] initWithNibName:#"SigninTabBarTemplateViewController" bundle:nil];
UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:self.viewController];
self.window.rootViewController = navController;
[self.window makeKeyAndVisible];
}
If you are signed out, I implement the tabbarcontroller as a separate UITabBarController like that:
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
UIViewController *viewController1 = [[FirstTab alloc] initWithNibName:#"FirstTab" bundle:NSBundle.mainBundle];
UINavigationController *firstNavController = [[UINavigationController alloc]initWithRootViewController:viewController1];
UIViewController *viewController2 = [[SecondTab alloc] initWithNibName:#"SecondTab" bundle:NSBundle.mainBundle];
UINavigationController *secondNavController = [[UINavigationController alloc]initWithRootViewController:viewController2];
myTabBarController = [[UITabBarController alloc] init];
myTabBarController.viewControllers = [NSArray arrayWithObjects:firstNavController, secondNavController, nil];
}
return self;
}
An elegant way to handle login states is to use a statemachine. The principle is, to define all possible states and the transitions between them. This might seem like an overkill on the first look, but as larger as your app grows, this investment will pay off.
For small apps, the if/else way should be fine.
#import <UIKit/UIKit.h>
#import "EditInfoViewController.h"
#interface ViewController : UIViewController <UITableViewDelegate, UITableViewDataSource, EditInfoViewControllerDelegate>
#property (weak, nonatomic) IBOutlet UITableView *tblPeople;
- (IBAction)addNewRecord:(id)sender;
#end
#import "ViewController.h"
#import "DBManager.h"
#interface ViewController ()
#property (nonatomic, strong) DBManager *dbManager;
#property (nonatomic, strong) NSArray *arrPeopleInfo;
#property (nonatomic) int recordIDToEdit;
-(void)loadData;
#end
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
// Make self the delegate and datasource of the table view.
self.tblPeople.delegate = self;
self.tblPeople.dataSource = self;
// Initialize the dbManager property.
self.dbManager = [[DBManager alloc] initWithDatabaseFilename:#"sampledb.sql"];
// Load the data.
[self loadData];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
EditInfoViewController *editInfoViewController = [segue destinationViewController];
editInfoViewController.delegate = self;
editInfoViewController.recordIDToEdit = self.recordIDToEdit;
}
#pragma mark - IBAction method implementation
- (IBAction)addNewRecord:(id)sender {
// Before performing the segue, set the -1 value to the recordIDToEdit. That way we'll indicate that we want to add a new record and not to edit an existing one.
self.recordIDToEdit = -1;
// Perform the segue.
[self performSegueWithIdentifier:#"idSegueEditInfo" sender:self];
}
#pragma mark - Private method implementation
-(void)loadData{
// Form the query.
NSString *query = #"select * from peopleInfo";
// Get the results.
if (self.arrPeopleInfo != nil) {
self.arrPeopleInfo = nil;
}
self.arrPeopleInfo = [[NSArray alloc] initWithArray:[self.dbManager loadDataFromDB:query]];
// Reload the table view.
[self.tblPeople reloadData];
}
#pragma mark - UITableView method implementation
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return self.arrPeopleInfo.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
// Dequeue the cell.
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"idCellRecord" forIndexPath:indexPath];
NSInteger indexOfFirstname = [self.dbManager.arrColumnNames indexOfObject:#"firstname"];
NSInteger indexOfLastname = [self.dbManager.arrColumnNames indexOfObject:#"lastname"];
NSInteger indexOfAge = [self.dbManager.arrColumnNames indexOfObject:#"age"];
// Set the loaded data to the appropriate cell labels.
cell.textLabel.text = [NSString stringWithFormat:#"%# %#", [[self.arrPeopleInfo objectAtIndex:indexPath.row] objectAtIndex:indexOfFirstname], [[self.arrPeopleInfo objectAtIndex:indexPath.row] objectAtIndex:indexOfLastname]];
cell.detailTextLabel.text = [NSString stringWithFormat:#"Age: %#", [[self.arrPeopleInfo objectAtIndex:indexPath.row] objectAtIndex:indexOfAge]];
return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
return 60.0;
}
-(void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath{
// Get the record ID of the selected name and set it to the recordIDToEdit property.
self.recordIDToEdit = [[[self.arrPeopleInfo objectAtIndex:indexPath.row] objectAtIndex:0] intValue];
// Perform the segue.
[self performSegueWithIdentifier:#"idSegueEditInfo" sender:self];
}
-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
if (editingStyle == UITableViewCellEditingStyleDelete) {
// Delete the selected record.
// Find the record ID.
int recordIDToDelete = [[[self.arrPeopleInfo objectAtIndex:indexPath.row] objectAtIndex:0] intValue];
// Prepare the query.
NSString *query = [NSString stringWithFormat:#"delete from peopleInfo where peopleInfoID=%d", recordIDToDelete];
// Execute the query.
[self.dbManager executeQuery:query];
// Reload the table view.
[self loadData];
}
}
#pragma mark - EditInfoViewControllerDelegate method implementation
-(void)editingInfoWasFinished{
// Reload the data.
[self loadData];
}
#end
===================
#import <UIKit/UIKit.h>
#protocol EditInfoViewControllerDelegate
-(void)editingInfoWasFinished;
#end
#interface EditInfoViewController : UIViewController <UITextFieldDelegate>
#property (nonatomic, strong) id<EditInfoViewControllerDelegate> delegate;
#property (weak, nonatomic) IBOutlet UITextField *txtFirstname;
#property (weak, nonatomic) IBOutlet UITextField *txtLastname;
#property (weak, nonatomic) IBOutlet UITextField *txtAge;
#property (nonatomic) int recordIDToEdit;
- (IBAction)saveInfo:(id)sender;
#end
#import "EditInfoViewController.h"
#import "DBManager.h"
#interface EditInfoViewController ()
#property (nonatomic, strong) DBManager *dbManager;
-(void)loadInfoToEdit;
#end
#implementation EditInfoViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
// Make self the delegate of the textfields.
self.txtFirstname.delegate = self;
self.txtLastname.delegate = self;
self.txtAge.delegate = self;
// Set the navigation bar tint color.
self.navigationController.navigationBar.tintColor = self.navigationItem.rightBarButtonItem.tintColor;
// Initialize the dbManager object.
self.dbManager = [[DBManager alloc] initWithDatabaseFilename:#"sampledb.sql"];
// Check if should load specific record for editing.
if (self.recordIDToEdit != -1) {
// Load the record with the specific ID from the database.
[self loadInfoToEdit];
}
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
/*
#pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
#pragma mark - UITextFieldDelegate method implementation
-(BOOL)textFieldShouldReturn:(UITextField *)textField{
[textField resignFirstResponder];
return YES;
}
#pragma mark - IBAction method implementation
- (IBAction)saveInfo:(id)sender {
// Prepare the query string.
// If the recordIDToEdit property has value other than -1, then create an update query. Otherwise create an insert query.
NSString *query;
if (self.recordIDToEdit == -1) {
query = [NSString stringWithFormat:#"insert into peopleInfo values(null, '%#', '%#', %d)", self.txtFirstname.text, self.txtLastname.text, [self.txtAge.text intValue]];
}
else{
query = [NSString stringWithFormat:#"update peopleInfo set firstname='%#', lastname='%#', age=%d where peopleInfoID=%d", self.txtFirstname.text, self.txtLastname.text, self.txtAge.text.intValue, self.recordIDToEdit];
}
// Execute the query.
[self.dbManager executeQuery:query];
// If the query was successfully executed then pop the view controller.
if (self.dbManager.affectedRows != 0) {
NSLog(#"Query was executed successfully. Affected rows = %d", self.dbManager.affectedRows);
// Inform the delegate that the editing was finished.
[self.delegate editingInfoWasFinished];
// Pop the view controller.
[self.navigationController popViewControllerAnimated:YES];
}
else{
NSLog(#"Could not execute the query.");
}
}
#pragma mark - Private method implementation
-(void)loadInfoToEdit{
// Create the query.
NSString *query = [NSString stringWithFormat:#"select * from peopleInfo where peopleInfoID=%d", self.recordIDToEdit];
// Load the relevant data.
NSArray *results = [[NSArray alloc] initWithArray:[self.dbManager loadDataFromDB:query]];
// Set the loaded data to the textfields.
self.txtFirstname.text = [[results objectAtIndex:0] objectAtIndex:[self.dbManager.arrColumnNames indexOfObject:#"firstname"]];
self.txtLastname.text = [[results objectAtIndex:0] objectAtIndex:[self.dbManager.arrColumnNames indexOfObject:#"lastname"]];
self.txtAge.text = [[results objectAtIndex:0] objectAtIndex:[self.dbManager.arrColumnNames indexOfObject:#"age"]];
}
#end
=====
===================
#import <Foundation/Foundation.h>
#interface DBManager : NSObject
#property (nonatomic, strong) NSMutableArray *arrColumnNames;
#property (nonatomic) int affectedRows;
#property (nonatomic) long long lastInsertedRowID;
-(instancetype)initWithDatabaseFilename:(NSString *)dbFilename;
-(NSArray *)loadDataFromDB:(NSString *)query;
-(void)executeQuery:(NSString *)query;
#end
#import "DBManager.h"
#import <sqlite3.h>
#interface DBManager()
#property (nonatomic, strong) NSString *documentsDirectory;
#property (nonatomic, strong) NSString *databaseFilename;
#property (nonatomic, strong) NSMutableArray *arrResults;
-(void)copyDatabaseIntoDocumentsDirectory;
-(void)runQuery:(const char *)query isQueryExecutable:(BOOL)queryExecutable;
#end
#implementation DBManager
#pragma mark - Initialization
-(instancetype)initWithDatabaseFilename:(NSString *)dbFilename{
self = [super init];
if (self) {
// Set the documents directory path to the documentsDirectory property.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
self.documentsDirectory = [paths objectAtIndex:0];
// Keep the database filename.
self.databaseFilename = dbFilename;
// Copy the database file into the documents directory if necessary.
[self copyDatabaseIntoDocumentsDirectory];
}
return self;
}
#pragma mark - Private method implementation
-(void)copyDatabaseIntoDocumentsDirectory{
// Check if the database file exists in the documents directory.
NSString *destinationPath = [self.documentsDirectory stringByAppendingPathComponent:self.databaseFilename];
if (![[NSFileManager defaultManager] fileExistsAtPath:destinationPath]) {
// The database file does not exist in the documents directory, so copy it from the main bundle now.
NSString *sourcePath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:self.databaseFilename];
NSError *error;
[[NSFileManager defaultManager] copyItemAtPath:sourcePath toPath:destinationPath error:&error];
// Check if any error occurred during copying and display it.
if (error != nil) {
NSLog(#"%#", [error localizedDescription]);
}
}
}
-(void)runQuery:(const char *)query isQueryExecutable:(BOOL)queryExecutable{
// Create a sqlite object.
sqlite3 *sqlite3Database;
// Set the database file path.
NSString *databasePath = [self.documentsDirectory stringByAppendingPathComponent:self.databaseFilename];
// Initialize the results array.
if (self.arrResults != nil) {
[self.arrResults removeAllObjects];
self.arrResults = nil;
}
self.arrResults = [[NSMutableArray alloc] init];
// Initialize the column names array.
if (self.arrColumnNames != nil) {
[self.arrColumnNames removeAllObjects];
self.arrColumnNames = nil;
}
self.arrColumnNames = [[NSMutableArray alloc] init];
// Open the database.
BOOL openDatabaseResult = sqlite3_open([databasePath UTF8String], &sqlite3Database);
if(openDatabaseResult == SQLITE_OK) {
// Declare a sqlite3_stmt object in which will be stored the query after having been compiled into a SQLite statement.
sqlite3_stmt *compiledStatement;
// Load all data from database to memory.
BOOL prepareStatementResult = sqlite3_prepare_v2(sqlite3Database, query, -1, &compiledStatement, NULL);
if(prepareStatementResult == SQLITE_OK) {
// Check if the query is non-executable.
if (!queryExecutable){
// In this case data must be loaded from the database.
// Declare an array to keep the data for each fetched row.
NSMutableArray *arrDataRow;
// Loop through the results and add them to the results array row by row.
while(sqlite3_step(compiledStatement) == SQLITE_ROW) {
// Initialize the mutable array that will contain the data of a fetched row.
arrDataRow = [[NSMutableArray alloc] init];
// Get the total number of columns.
int totalColumns = sqlite3_column_count(compiledStatement);
// Go through all columns and fetch each column data.
for (int i=0; i<totalColumns; i++){
// Convert the column data to text (characters).
char *dbDataAsChars = (char *)sqlite3_column_text(compiledStatement, i);
// If there are contents in the currenct column (field) then add them to the current row array.
if (dbDataAsChars != NULL) {
// Convert the characters to string.
[arrDataRow addObject:[NSString stringWithUTF8String:dbDataAsChars]];
}
// Keep the current column name.
if (self.arrColumnNames.count != totalColumns) {
dbDataAsChars = (char *)sqlite3_column_name(compiledStatement, i);
[self.arrColumnNames addObject:[NSString stringWithUTF8String:dbDataAsChars]];
}
}
// Store each fetched data row in the results array, but first check if there is actually data.
if (arrDataRow.count > 0) {
[self.arrResults addObject:arrDataRow];
}
}
}
else {
// This is the case of an executable query (insert, update, ...).
// Execute the query.
BOOL executeQueryResults = sqlite3_step(compiledStatement);
if (executeQueryResults == SQLITE_DONE) {
// Keep the affected rows.
self.affectedRows = sqlite3_changes(sqlite3Database);
// Keep the last inserted row ID.
self.lastInsertedRowID = sqlite3_last_insert_rowid(sqlite3Database);
}
else {
// If could not execute the query show the error message on the debugger.
NSLog(#"DB Error: %s", sqlite3_errmsg(sqlite3Database));
}
}
}
else {
// In the database cannot be opened then show the error message on the debugger.
NSLog(#"%s", sqlite3_errmsg(sqlite3Database));
}
// Release the compiled statement from memory.
sqlite3_finalize(compiledStatement);
}
// Close the database.
sqlite3_close(sqlite3Database);
}
#pragma mark - Public method implementation
-(NSArray *)loadDataFromDB:(NSString *)query{
// Run the query and indicate that is not executable.
// The query string is converted to a char* object.
[self runQuery:[query UTF8String] isQueryExecutable:NO];
// Returned the loaded results.
return (NSArray *)self.arrResults;
}
-(void)executeQuery:(NSString *)query{
// Run the query and indicate that is executable.
[self runQuery:[query UTF8String] isQueryExecutable:YES];
}
#end
enter code here
#interface ViewController ()
{ sqlite3 *dbref;
NSString *dbpath;
BOOL flag;}
#end
#implementation ViewController
#synthesize usertxt,passtxt;
- (void)viewDidLoad
{[super viewDidLoad];
NSString *docpath;
NSError *error;
NSArray *docarr=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSLog(#"directory path=%#",docarr);
docpath=[docarr objectAtIndex:0];
// docpath=[docpath stringByAppendingString:#"/simpledb.sqlite/"];
[[NSFileManager defaultManager] createDirectoryAtPath:docpath withIntermediateDirectories:YES attributes:nil error:&error];
dbpath=[[NSString alloc] initWithString:[docpath stringByAppendingString:#"/simpledb.sqlite"]];
NSFileManager *fmgr=[NSFileManager defaultManager];
if([fmgr fileExistsAtPath:dbpath]!=YES)
{ char *err;
const char *dbp=[dbpath UTF8String];
if(sqlite3_open(dbp, &dbref)==SQLITE_OK)
{ const char *crstmt = "CREATE TABLE IF NOT EXISTS Login(Login_id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,Username TEXT , Password TEXT)";
if(sqlite3_exec(dbref, crstmt, NULL, NULL,&err)!= SQLITE_OK)
{
}
sqlite3_close(dbref);
}}
// Do any additional setup after loading the view, typically from a nib.
}
-(IBAction)save:(id)sender
{[self validation];
if(flag==0)
{ sqlite3_stmt *statement;
NSString *insertSQL = [NSString stringWithFormat:#"insert into Login(Username,Password) values('%#','%#')",usertxt.text,passtxt.text];
const char *insert_stmt = [insertSQL UTF8String];
const char *dbp=[dbpath UTF8String];
if(sqlite3_open(dbp, &dbref)==SQLITE_OK)
{ sqlite3_prepare_v2(dbref, insert_stmt, -1, &statement, NULL);
if (sqlite3_step(statement) == SQLITE_DONE)
{
}
else
{
}}
sqlite3_finalize(statement);
sqlite3_close(dbref);
UIAlertView *objalert=[[UIAlertView alloc]initWithTitle:#"Inserted Successfully" message:nil delegate:nil cancelButtonTitle:#"cancel" otherButtonTitles:#"ok", nil];
[objalert show];
}}
-(IBAction)update:(id)sender
{ NSString *querySQL = [NSString stringWithFormat: #"update Login set Username='%#',Password='%#' where Login_id==1",usertxt.text,passtxt.text];
[self updateQuery:querySQL];}
-(BOOL)updateQuery:(NSString *)querySQL
{ sqlite3_stmt *statement;
const char *dbp=[dbpath UTF8String];
if(sqlite3_open(dbp, &dbref)==SQLITE_OK)
{ const char *query_stmt = [querySQL UTF8String];
if (sqlite3_prepare_v2(dbref, query_stmt, -1, &statement, NULL) == SQLITE_OK)
{ if (sqlite3_step(statement) == SQLITE_ROW)
{ sqlite3_reset(statement);
return YES;
} }
sqlite3_finalize(statement);
sqlite3_close(dbref)}
else
{ return NO;
}
return YES}
-(void)validation
{ NSString *valida;
// usertxt.text = [usertxt.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
// passtxt.text = [passtxt.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
if ([usertxt.text length]<2)
{flag=1;
valida=#"user Name : Minimum 2 Character req*\n";
UIAlertView *objalert=[[UIAlertView alloc]initWithTitle:nil message:valida delegate:nil cancelButtonTitle:nil otherButtonTitles:#"ok", nil];
[objalert show];
}
}
#imp flipsideviewcont
#syn entries
-(void)viewdidload
{
entries=[[nsmutablarray alloc]onit];
[self opendb];
nsstring *sql=[nsstring stringwithormat:#"select * from summery"];
sqlite_state *stat;
if(sqlite_prepare_v2(db,[sql utf8string],-1,&stat,nil)==sqlite_ok)
{while(sqlite_step(stat==sqlite_row))
{
char *field1=(char*)sqlite_column_text(stat,0);
nsstring *field1str=[[nsstring alloc]initwithutf8string:feild1];
char *field2=(char*)sqlite_column_text(stat,1);
nsstring *field2str=[[nsstring alloc]initwithutf8string:feild2];
nsstring *str=[[nsstring alloc]initwithformat:#"%#/%#-%#",field2str,field3str,field4str];
[entries addobjects:str];
}
-(nsstring*)filepath
{
nsarray *path=nssearchpathfordocumentry(nsdocumentdic,nsdomainmask,yes);
return([path objectAtindex:0]stringbyappingpathcomp:#"ss.sql");
}
-(void)opendb
{
if(sqlite_open([self filepath]utf8string,&db)!=sqlite_ok)
{sqlite_close(db);
nsasser(0,#"problem");
else
{
nslog(#"db open");
}
}
-(ibaction)done
{
[self.delegate flipsideviewcontrollerdidfinish :self];
}
cellforindex
{
cell.textlabel.text=[self.entries objectAtindex:indexpath:row];
}
===========================interface flipsideviewcont======
#import "sqlite3.h"
#class flipsideviewcontroller;
-(void)flipsideviewcontdidfinish:(flipsideviewcontroller*)controller;
#end
#interface flipsideviewcont:viewcont
{
sqlite *db;
}
#property()id<flipsideviewcontrollerdelegate>delegate;
#property()nsmutablearray *entries;
-(void)opendb;
-(nsstring*)filepath;
}
======================
#interface mainviewcontroller:viewcontroller<flipsideviewcontrollerdelegate>
{sqlite3 *db;}
#property()iboutlet nstextfiled *systext,*diatext,*commenttxt;
#property(readpnly,non)nsdate *currentdate;
-(void)createTable:(nsstring*)tablename
withfield1:(nsstring*)field1 withfield2:(nsstring*)field2 withfield3:(nsstring*)field3 withfield4:(nsstring*)field4;
-(ibaction)saveentry;
#implement mainview
-(void)createTable:(nsstring*)tablename
withfield1:(nsstring*)field1 withfield2:(nsstring*)field2 withfield3:(nsstring*)field3 withfield4:(nsstring*)field4
{
char *err;
nastring *sql=[nsstring stringwithformat:#"crete table if nat exist '%#'('%#'""text primary key,'%#' int,'%#' int,'%#'text);",tablename,field1,field2,field3,field4);
if(sqlite_exe(db,[sql utf*string],null,null,&err)!=sqlite_ok)
{sqlite_close(db);
}}
-(void)opendb;
{}
-(nsstring*)filepath()
-(void)viewdidload
{[self opendb];
[self createtable:#"summery" withfield:#"thedate withfield2:#"systonic"];}
-(ibaction)saveenrty
{
int sys=[systext.text intvalue];
int dia=[diatext.text intvalue];
nsstring *comm=comtext.tex;
nsdate *thedate=[nsdate date];
nsstring *sql=[nsstring stringwithformat:#"insert into summery('sys','thedate','dia',''com')values('%#','%d','%d','%#')",thedate,sys,dia,comm];
{sqlite_close(db);
}
systext.text="";
didtext.text="";
commtext.text="";
}
}
-(void)prepareforsegue
{if([[segue identifier]isequalto string:#"showwale");
{[[segue destinationviewcont]setdelegate:self];
}
}
-(void)flipsideviewcontdidfinish
{[self dismissviewcontroller:yes];
}
}
}

objects in nsmutablearray becoming zombies

i am developing very simple quiz app
In viewDidLoad i am adding objects in myarray
where ever i nslog myarray values it works fine
but if i try this inside ibaction methods all objects becomes zombie
for 2 days i am stuck in this but can't find it what is wrong.
quiz.h
#import <UIKit/UIKit.h>
#import <sqlite3.h>
#class dbVals;
#class viewTransition;
#class AppDelegate;
#interface quiz : UIViewController
{
NSMutableArray *myarray;
IBOutlet UITextView *questionTextView_;
IBOutlet UIButton *skipButton_;
IBOutlet UIButton *optionAButton_;
IBOutlet UIButton *optionBButton_;
IBOutlet UIButton *optionCButton_;
NSString *correctAnswer;
int questionNumber;
int score;
IBOutlet UILabel *scoreLabel_;
int totalQuestions;
}
-(void)populate:(int)number;
//#property(nonatomic, retain) NSMutableArray *myarray;
#property (retain, nonatomic) IBOutlet UITextView *questionTextView;
#property (retain, nonatomic) IBOutlet UIButton *skipButton;
#property (retain, nonatomic) IBOutlet UIButton *optionAButton;
#property (retain, nonatomic) IBOutlet UIButton *optionBButton;
#property (retain, nonatomic) IBOutlet UIButton *optionCButton;
#property (retain, nonatomic) IBOutlet UILabel *scoreLabel;
- (IBAction)optionsToAnswer:(id)sender;
- (IBAction)zzz:(id)sender;
#end
quiz.m
#import "quiz.h"
#import "DbVals.h"
#import "viewTransition.h"
#import "AppDelegate.h"
#implementation quiz
#synthesize skipButton=skipButton_;
#synthesize optionAButton=optionAButton_;
#synthesize optionBButton=optionBButton_;
#synthesize optionCButton=optionCButton_;
#synthesize scoreLabel=scoreLabel_;
#synthesize questionTextView=questionTextView_;
//#synthesize myarray;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)didReceiveMemoryWarning
{
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
#pragma mark - View lifecycle
- (void)createEditableCopyOfDatabaseIfNeeded
{
//NSLog(#"Creating editable copy of database");
// First, test for existence.
BOOL success;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:#"oq.sqlite"];
success = [fileManager fileExistsAtPath:writableDBPath];
if (success) return;
// The writable database does not exist, so copy the default to the appropriate location.
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"oq.sqlite"];
success = [fileManager copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error];
if (!success) {
NSAssert1(0, #"Failed to create writable database file with message '%#'.", [error localizedDescription]);
}
}
+(sqlite3 *) getNewDBConnection
{
sqlite3 *newDBconnection;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:#"oq.sqlite"];
// Open the database. The database was prepared outside the application.
if (sqlite3_open([path UTF8String], &newDBconnection) == SQLITE_OK) {
//NSLog(#"Database Successfully Opened ");
} else {
NSLog(#"Error in opening database ");
}
return newDBconnection;
}
- (void)viewDidLoad
{
[super viewDidLoad];
questionNumber = 0;
score = 0;
[self createEditableCopyOfDatabaseIfNeeded];
sqlite3 *dbc = [quiz getNewDBConnection];
sqlite3_stmt *statement = nil;
const char *sqlSelect = "select * from QnA ORDER BY RANDOM()";
if(sqlite3_prepare_v2(dbc, sqlSelect, -1, &statement, NULL)!=SQLITE_OK)
{
NSAssert1(0, #"Error Preparing Statement", sqlite3_errmsg(dbc));
}
else
{
myarray = [[NSMutableArray alloc]init];
while(sqlite3_step(statement)==SQLITE_ROW)
{
NSString *q = [NSString stringWithUTF8String:(char *) sqlite3_column_text(statement, 0)];
NSString *o = [NSString stringWithUTF8String:(char *) sqlite3_column_text(statement, 1)];
NSString *a = [NSString stringWithUTF8String:(char *) sqlite3_column_text(statement, 2)];
DbVals *dbValsObj = [[DbVals alloc]init];
[dbValsObj setValsOfQuestions:q options:o answer:a];
[myarray addObject:dbValsObj];
[dbValsObj release];
}
}
sqlite3_finalize(statement);
//[self populate:questionNumber];
}
-(void)populate:(int)number
{
/*[scoreLabel_ setText:[NSString stringWithFormat:#"%d",score]];
AppDelegate *appDel = [[UIApplication sharedApplication] delegate];
[appDel setFinalScore:[NSString stringWithFormat:#"%d",score]];
if(number < [myarray count])
{
DbVals *dbv1 = [myarray objectAtIndex:number];
[questionTextView_ setText:[dbv1 getQuestions]];
NSString *joinedOptions = [dbv1 getOptions];
NSArray *splitOptions = [joinedOptions componentsSeparatedByString:#","];
[optionAButton_ setTitle:[splitOptions objectAtIndex:0] forState:UIControlStateNormal];
[optionBButton_ setTitle:[splitOptions objectAtIndex:1] forState:UIControlStateNormal];
[optionCButton_ setTitle:[splitOptions objectAtIndex:2] forState:UIControlStateNormal];
correctAnswer = [dbv1 getAnswer];
}
else
{
//viewTransition *vt = [[viewTransition alloc]init];
[viewTransition viewsTransitionCurrentView:self toNextView:#"result"];
//[vt release];
}*/
}
- (void)viewDidUnload
{
for(int i=0; i<[myarray count]; i++)
{
DbVals *dbv1 = [myarray objectAtIndex:i];
NSLog(#"%#",[dbv1 getQuestions]);
NSLog(#"%#",[dbv1 getOptions]);
NSLog(#"%#",[dbv1 getAnswer]);
NSLog(#"<u><u><u><u><><><><><><><><><><><>");
}
[self setQuestionTextView:nil];
[questionTextView_ release];
questionTextView_ = nil;
[self setQuestionTextView:nil];
[skipButton_ release];
skipButton_ = nil;
[self setSkipButton:nil];
[optionAButton_ release];
optionAButton_ = nil;
[self setOptionAButton:nil];
[optionBButton_ release];
optionBButton_ = nil;
[self setOptionBButton:nil];
[optionCButton_ release];
optionCButton_ = nil;
[self setOptionCButton:nil];
[scoreLabel_ release];
scoreLabel_ = nil;
[self setScoreLabel:nil];
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void)dealloc
{
for(int i=0; i<[myarray count]; i++)
{
DbVals *dbv1 = [myarray objectAtIndex:i];
NSLog(#"%#",[dbv1 getQuestions]);
NSLog(#"%#",[dbv1 getOptions]);
NSLog(#"%#",[dbv1 getAnswer]);
NSLog(#"<d><d><d><d><d><><><><><><><><><><>");
}
[questionTextView_ release];
[skipButton_ release];
[optionAButton_ release];
[optionBButton_ release];
[optionCButton_ release];
[scoreLabel_ release];
[myarray release];
[super dealloc];
}
- (IBAction)optionsToAnswer:(id)sender
{
for(int i=0; i<[myarray count]; i++)
{
DbVals *dbv1 = [myarray objectAtIndex:i];
NSLog(#"%#",[dbv1 getQuestions]);
NSLog(#"%#",[dbv1 getOptions]);
NSLog(#"%#",[dbv1 getAnswer]);
NSLog(#"six");
}
if(sender == skipButton_)
{
//questionNumber++;
//[self populate:questionNumber];
/*[UIView animateWithDuration:5 delay:0 options: UIViewAnimationCurveEaseOut
animations:
^{
[UIView setAnimationTransition:103 forView:self.view cache:NO];
}
completion:
^(BOOL finished)
{
}
];*/
}
if(sender == optionAButton_)
{
/*NSString *one = #"1";
if([correctAnswer isEqualToString:one])
{
score++;
}
questionNumber++;
[self populate:questionNumber];*/
}
if(sender == optionBButton_)
{
/*NSString *two = #"2";
if([correctAnswer isEqualToString:two])
{
score++;
}
questionNumber++;
[self populate:questionNumber];*/
}
if(sender == optionCButton_)
{
/*NSString *three = #"3";
if([correctAnswer isEqualToString:three])
{
score++;
}
questionNumber++;
[self populate:questionNumber];*/
}
}
- (IBAction)zzz:(id)sender
{
}
#end
dbVals.h
#import <Foundation/Foundation.h>
#interface DbVals : NSObject
{
NSString *questions_;
NSString *options_;
NSString *answer_;
// NSString *hint;
// NSString *mode;
}
-(void)setValsOfQuestions:(NSString*)questions options:(NSString*)options answer:(NSString*)answer;
-(NSString*)getQuestions;
-(NSString*)getOptions;
-(NSString*)getAnswer;
dbVals.m
#import "DbVals.h"
#implementation DbVals
-(void)setValsOfQuestions:(NSString*)questions options:(NSString*)options answer:(NSString*)answer
{
questions_ = questions;
options_ = options;
answer_ = answer;
}
-(NSString*)getQuestions
{
return questions_;
}
-(NSString*)getOptions
{
return options_;
}
-(NSString*)getAnswer
{
return answer_;
}
#end
Your dbVals.m setVals isn't retaining the parameters. This obviously means, everything inside becomes deallocated once the function scope ends.
Try changing it to something like
-(void)setValsOfQuestions:(NSString*)questions options:(NSString*)options answer:(NSString*)answer
{
[questions_ release];
[options_ release];
[answer_ release];
questions_ = [questions copy];
options_ = [options copy];
answer_ = [answer copy];
}

Resources