objects in nsmutablearray becoming zombies - ios

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];
}

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

can't add the Dynamic values in Pie Carts [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
//
// PieChartTest.m
// Yazaki
//
// Created by apple on 3/25/16.
// Copyright (c) 2016 apple. All rights reserved.
//
#import "PieChartTest.h"
#import "testingvc.h"
#interface PieChartTest ()
#property (strong, nonatomic) NSMutableArray *values;
#property (strong, nonatomic) NSMutableArray *testARYY;
#property (strong, nonatomic) NSMutableArray *labels;
#property (strong, nonatomic) NSMutableArray *colors;
#property (nonatomic) BOOL inserting;
#property (strong, nonatomic) NSArray *colors1;
#property (strong, nonatomic) NSDictionary *serviceResponse;
#property(strong,nonatomic) NSString *item;
#property(strong,nonatomic) NSArray *temp;
#property (strong, nonatomic) NSDictionary *sample;
#end
#implementation PieChartTest
#synthesize dictObject;
#synthesize str1;
#synthesize str2;
- (void)viewDidLoad {
[super viewDidLoad];
NSString *baseURL = [NSString stringWithFormat:#"http://192.168.1.122:8099/YazakiService.svc/SESSION/%#/%#/%#",dictObject,str1,str2];
NSURL *url = [NSURL URLWithString:[baseURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
NSURLResponse *response;
NSError *error;
NSData *responseData =[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
_serviceResponse=[NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers error:&error];
NSArray *temp = [_serviceResponse objectForKey:#"SESSIONCOUNT"];
NSDictionary *sample=[temp objectAtIndex:0];
NSString*item=[sample objectForKey:#"COUNTVALUE"];
if( [_serviceResponse objectForKey:#"SESSIONCOUNT"] == nil ||
[[_serviceResponse objectForKey:#"SESSIONCOUNT"] isEqual:[NSNull null]] ){
// do nothing
}else
{
NSArray *temp = [_serviceResponse objectForKey:#"SESSIONCOUNT"];
if ([temp isKindOfClass:[NSArray class]] && temp.count !=0)
{
// value is available
[self.values removeAllObjects];
self.values = [NSMutableArray new];
int i;
for (i=0; i<[temp count]; i++) {
[self.values addObject:[NSString stringWithFormat:#"%#",[[temp objectAtIndex:i] objectForKey:#"COUNTVALUE"]]];
[self.values addObject:[NSString stringWithFormat:#"%#",[[temp objectAtIndex:i] objectForKey:#"SESSIONVALUE"]]];
}
}
}
self.pieChartView.dataSource = self;
self.pieChartView.delegate = self;
self.pieChartView.animationDuration = 0.5;
self.pieChartView.sliceColor = [MCUtil flatWetAsphaltColor];
self.pieChartView.borderColor = [MCUtil flatSunFlowerColor];
self.pieChartView.selectedSliceColor = [MCUtil flatSunFlowerColor];
self.pieChartView.textColor = [MCUtil flatSunFlowerColor];
self.pieChartView.selectedTextColor = [MCUtil flatWetAsphaltColor];
self.pieChartView.borderPercentage = 0.01;
}
- (NSInteger)numberOfSlicesInPieChartView:(MCPieChartView *)pieChartView {
return self.values.count;
}
- (CGFloat)pieChartView:(MCPieChartView *)pieChartView valueForSliceAtIndex:(NSInteger)index {
return [[self.values objectAtIndex:index] floatValue];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)pieChartView:(MCPieChartView*)pieChartView didSelectSliceAtIndex:(NSInteger)index;
{
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:#"Main" bundle:nil];
testingvc *destViewController = (testingvc*)[storyboard instantiateViewControllerWithIdentifier:#"testing"];
self.values = [_serviceResponse objectForKey:#"SESSIONCOUNT"];
// //destViewController = [CategoryVC.destViewController objectAtIndex:0];
NSDictionary *sample=[self.values objectAtIndex:index];
NSString*item=[sample objectForKey:#"SESSIONVALUE"];
//
destViewController.category = item;
destViewController.STATUS =dictObject;
destViewController.fromDate=str1;
destViewController.Todate=str2;
[destViewController setModalPresentationStyle:UIModalPresentationFullScreen];
[self presentViewController:destViewController animated:NO completion:nil];
}
#end
i got the error while select the 4th slice index ...i got the crash of
2016-03-31 11:40:10.582 Yazaki[2150:37777] * Terminating app due to uncaught exception 'NSRangeException', reason: '* -[__NSArrayM objectAtIndex:]: index 4 beyond bounds [0 .. 3]'
*** First throw call stack:
change this
self.values=[_serviceResponse objectForKey:#"SESSIONCOUNT"];
NSLog(#"got response==%#", self.values);
int i;
for (i=0; i<[self.values count]; i++) {
NSDictionary *exp=[self.values objectAtIndex:i];
_item=[exp objectForKey:#"COUNTVALUE"];
//[self.testARYY addObject:item];
}
[self.values addObject:_item];
into and try
NSArray *temp = [_serviceResponse objectForKey:#"SESSIONCOUNT"];
if (temp.count>0)
{
[self.values removeAllObjects];
self.values = [NSMutableArray new];
for (i=0; i<[temp count]; i++) {
[self.values addObject:[NSString Stringwithformat:#"%#",[[temp objectAtIndex:i] objectForKey:#"COUNTVALUE"]]];
}
}
or use like
Choice-2
NSArray *temp = [_serviceResponse objectForKey:#"SESSIONCOUNT"];
if ([temp isKindOfClass:[NSArray class]] && temp.count !=0)
{
// value is available
[self.values removeAllObjects];
self.values = [NSMutableArray new];
for (i=0; i<[temp count]; i++) {
[self.values addObject:[NSString Stringwithformat:#"%#",[[temp objectAtIndex:i] objectForKey:#"COUNTVALUE"]]];
}
}
Update-2
if( [_serviceResponse objectForKey:#"SESSIONCOUNT"] == nil ||
[[_serviceResponse objectForKey:#"SESSIONCOUNT"] isEqual:[NSNull null]] ){
// do nothing
}else
{
NSArray *temp = [_serviceResponse objectForKey:#"SESSIONCOUNT"];
if ([temp isKindOfClass:[NSArray class]] && temp.count !=0)
{
// value is available
[self.values removeAllObjects];
self.values = [NSMutableArray new];
for (i=0; i<[temp count]; i++) {
[self.values addObject:[NSString Stringwithformat:#"%#",[[temp objectAtIndex:i] objectForKey:#"COUNTVALUE"]]];
}
}
}
You should try to change this line:
return [[self.values objectAtIndex:index] floatValue];
to this
return [[self.values objectAtIndex:index][#"COUNTVALUE"] floatValue];
The error says that you are trying to call the floatValue function on a NSMutableDictionary, from my understanding you should call it on the value stored under the "COUNTVALUE" key of the dictionary.

iOS Tolo bus REGISTER() macro wierd behavior

I have an ordinary Database manager class. Here is the code:
#import "DatabaseManager.h"
#import "Tolo.h"
#import "Action.h"
#import "ActionCreatorConstants.h"
#import <sqlite3.h>
#import "DatabaseConstants.h"
#import "KGKSignal.h"
#interface DatabaseManager ()
#property (nonatomic, strong) NSString *documentsDirectory;
#property (nonatomic, strong) NSString *databaseFilename;
#property (nonatomic, strong) NSMutableArray *arrayResults;
#property (nonatomic, strong) NSMutableArray *arrayColumnNames;
#property (nonatomic) int affectedRows;
#property (nonatomic) long long lastInsertedRowID;
#end
#implementation DatabaseManager
static DatabaseManager *instance = nil;
+ (instancetype)getInstance {
if (instance == nil) {
instance = [[DatabaseManager alloc] initWithDatabaseFilename:DATABASE_NAME];
}
return instance;
}
- (instancetype)initWithDatabaseFilename:(NSString *)databaseFilename {
self = [super init];
if (self) {
REGISTER();
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, YES);
self.documentsDirectory = [paths objectAtIndex:0];
self.databaseFilename = databaseFilename;
// [self copyDatabaseIntoDocumentsDirectory];
}
return self;
}
- (void)copyDatabaseIntoDocumentsDirectory {
NSString *destinationPath = [self.documentsDirectory stringByAppendingPathComponent:self.databaseFilename];
if (![[NSFileManager defaultManager] fileExistsAtPath:destinationPath]) {
NSString *sourcePath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:self.databaseFilename];
NSError *error;
[[NSFileManager defaultManager] copyItemAtPath:sourcePath
toPath:destinationPath
error:&error];
if (error != nil) {
NSLog(#"%#", [error localizedDescription]);
}
}
}
- (void)runQuery:(const char *)query isQueryExecutable:(BOOL)queryExecutable {
sqlite3 *sqlite3Database;
// NSString *databasePath = [self.documentsDirectory
// stringByAppendingPathComponent:self.databaseFilename];
NSString *databasePath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:DATABASE_NAME];
if (self.arrayResults != nil) {
[self.arrayResults removeAllObjects];
self.arrayResults = nil;
}
self.arrayResults = [[NSMutableArray alloc] init];
if (self.arrayColumnNames != nil) {
[self.arrayColumnNames removeAllObjects];
self.arrayColumnNames = nil;
}
self.arrayColumnNames = [[NSMutableArray alloc] init];
BOOL openDatabaseResult = sqlite3_open([databasePath UTF8String], &sqlite3Database);
if (openDatabaseResult == SQLITE_OK) {
sqlite3_stmt *compiledStatement;
BOOL preparedStatementResult = sqlite3_prepare_v2(sqlite3Database, query, -1,
&compiledStatement, NULL);
if (preparedStatementResult == SQLITE_OK) {
if (!queryExecutable) {
NSMutableArray *arrayDataRow;
while (sqlite3_step(compiledStatement) == SQLITE_ROW) {
arrayDataRow = [[NSMutableArray alloc] init];
int totalColumns = sqlite3_column_count(compiledStatement);
for (int i = 0; i < totalColumns; i++) {
char *dbDataAsChars = (char *)sqlite3_column_text(compiledStatement, i);
if (dbDataAsChars != NULL) {
[arrayDataRow addObject:[NSString stringWithUTF8String:dbDataAsChars]];
}
if (self.arrayColumnNames.count != totalColumns) {
dbDataAsChars = (char *)sqlite3_column_name(compiledStatement, i);
[self.arrayColumnNames addObject:[NSString stringWithUTF8String:dbDataAsChars]];
}
}
if (arrayDataRow.count > 0) {
[self.arrayResults addObject:arrayDataRow];
}
}
} else {
BOOL executeQueryResult = sqlite3_step(compiledStatement);
if (executeQueryResult) {
self.affectedRows = sqlite3_changes(sqlite3Database);
self.lastInsertedRowID = sqlite3_last_insert_rowid(sqlite3Database);
} else {
NSLog(#"Database error: %s", sqlite3_errmsg(sqlite3Database));
}
}
} else {
NSLog(#"%s", sqlite3_errmsg(sqlite3Database));
}
sqlite3_finalize(compiledStatement);
}
sqlite3_close(sqlite3Database);
}
- (NSArray *)loadDataFromDatabase:(NSString *)query {
[self runQuery:[query UTF8String] isQueryExecutable:NO];
return (NSArray *)self.arrayResults;
}
- (void)executeQuery:(NSString *)query {
[self runQuery:[query UTF8String] isQueryExecutable:YES];
}
SUBSCRIBE(Action) {
if ([event.type isEqualToString:GET_LAST_SIGNAL_DATE_FROM_DATABASE]) {
NSLog(#"Lal");
}
}
- (void)insertSignal:(KGKSignal *)signal {
NSString *insertSignalQuery = [NSString stringWithFormat:#"INSERT INTO %# (%#,%#,%#,%#,%#,%#,%#,%#,%#,%#,%#,%#) VALUES (%ld,%ld,%f,%f,%ld,%f,%f,%ld,%ld,%ld,%ld,%ld);", TABLE_SIGNAL, COLUMN_DEVICE_ID, COLUMN_MODE, COLUMN_LATITUDE, COLUMN_LONGITUDE, COLUMN_DATE, COLUMN_VOLTAGE, COLUMN_BALANCE, COLUMN_SATELLITES, COLUMN_SPEED, COLUMN_CHARGE, COLUMN_DIRECTION, COLUMN_TEMPERATURE, (long)signal.deviceId, (long)signal.mode, signal.latitude, signal.longitude, (long)signal.date, signal.voltage, signal.balance, (long)signal.satellites, (long)signal.speed, (long)signal.charge, (long)signal.direction, (long)signal.temperature];
[self executeQuery:insertSignalQuery];
}
- (NSInteger)getLastSignalDate {
NSInteger lastSignalDate = 1441065600;
return lastSignalDate;
}
#end
The problem lurks in the last method - getLastSignalDate. When i set return value to 0 - app works ok. When method returns any non-null number - app craches in runtime (build successful). Error occurs in Tolo object - it can not register (Via REGISTER() macro) Database Manager object - EXC_BAD_ACCESS error in publish method of Tolo.m. Did someone face with same wierd behavior???
I've overriden dealloc method of Database Manager and it didn't log before error occured - so object exists in memory.

IOS dev: Just need help in exc_bad_access error

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.

Displaying Integer value in a Label , int to String conversion?

How to display an integer value in a UILabel in ViewDidLoad? I did for text and date and image but how to convert int to string. I was trying with following code
NSString* label=[aa stringWithFormat:#"%d",((Comments *) [self.list objectAtIndex:0]).noofcomm]];
[self.comments2 setText:label];
but didn't work.Please help me.How to set with the Integer with UILabel?
This is my comments.h
#interface Comments : NSObject
{
NSInteger iD;
UIImage *photo;
NSString *name;
NSString *descrp;
NSDate *date;
NSString *msg;
NSInteger noofcomm;
NSInteger nooflikes;
}
#property(nonatomic,assign)NSInteger iD;
#property(nonatomic,retain)UIImage *photo;
#property(nonatomic,retain)NSString *name;
#property(nonatomic,retain)NSString *descrp;
#property(nonatomic,strong)NSDate *date;
#property(nonatomic,retain)NSString *msg;
#property(nonatomic,assign)NSInteger noofcomm;
#property(nonatomic,assign)NSInteger nooflikes;
#end
DBClass.m
#import "DBClass.h"
#import "Comments.h"
#implementation DBClass
- (NSMutableArray *) getMyComments{
NSMutableArray *wineArray = [[NSMutableArray alloc] init];
#try {
NSFileManager *fileMgr = [NSFileManager defaultManager];
NSString *dbPath = [[[NSBundle mainBundle] resourcePath ]stringByAppendingPathComponent:#"ComntDB.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 id, photo,name,descrp, time,msg,comments,likes FROM Com";
sqlite3_stmt *sqlStatement;
if(sqlite3_prepare(db, sql, -1, &sqlStatement, NULL) != SQLITE_OK)
{
NSLog(#"Problem with prepare statement");
}
//
while (sqlite3_step(sqlStatement)==SQLITE_ROW) {
Comments *MyWine = [[Comments alloc]init];
MyWine.iD = sqlite3_column_int(sqlStatement, 0);
const char *raw = sqlite3_column_blob(sqlStatement, 1);
int rawLen = sqlite3_column_bytes(sqlStatement, 1);
NSData *data = [NSData dataWithBytes:raw length:rawLen];
MyWine.photo = [[UIImage alloc] initWithData:data];
MyWine.name = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement,2)];
MyWine.descrp = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement, 3)];
MyWine.date=[NSDate dateWithTimeIntervalSince1970:sqlite3_column_double(sqlStatement,4)];
MyWine.msg = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement,5)];
MyWine.noofcomm = sqlite3_column_int(sqlStatement, 6);
MyWine.nooflikes = sqlite3_column_int(sqlStatement, 7);
[wineArray addObject:MyWine];
}
}
#catch (NSException *exception) {
NSLog(#"An exception occured: %#", [exception reason]);
}
#finally {
return wineArray;
}
}
#end
RootViewController.m
#import "RootViewController.h"
#import "Comments.h"
#import "DBClass.h"
#interface RootViewController ()
#end
#implementation RootViewController
#synthesize list;
#synthesize image2;
#synthesize name2;
#synthesize descrp2;
#synthesize msg2;
#synthesize date2;
#synthesize comments2;
#synthesize likes2;
- (void)viewDidLoad
{
DBClass * mywines =[[DBClass alloc] init];
self.list = [mywines getMyComments];
[self.image2 setImage:((Comments *) [self.list objectAtIndex:0]).photo];
[self.name2 setText:((Comments *) [self.list objectAtIndex:0]).name];
[self.descrp2 setText:((Comments *) [self.list objectAtIndex:0]).descrp];
NSDateFormatter* fmtr = [[NSDateFormatter alloc] init];
[fmtr setDateFormat:#"MM/dd/yy"];
NSString* label_str = [fmtr stringFromDate:((Comments *) [self.list objectAtIndex:0]).date];
[self.date2 setText:label_str];
[self.msg2 setText:((Comments *) [self.list objectAtIndex:0]).msg];
//[self.comments2 setText:((Comments *) [self.list objectAtIndex:0]).noofcomm];
// int solution = 1;
// [self.comments2 setText:[NSString stringWithFormat:#"%d", solution]];
// int solution2 = 1;
// [self.likes2 setText:[NSString stringWithFormat:#"%d", solution2]];
[super viewDidLoad];
}
- (void)viewDidUnload
{
[self setImage2:nil];
[self setName2:nil];
[self setMsg2:nil];
[self setDescrp2:nil];
[self setComments2:nil];
[self setLikes2:nil];
[self setDate2:nil];
[super viewDidUnload];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
NSInteger someInteger = myInteger;
NSString *someString = [NSString stringWithFormat:#"%d", someInteger];
myLabel.text = someString;
or
NSNumber *someNumber = #(myInteger);
NSString *someString = [someNumber stringValue];
myLabel.text = someString;
Both will work.
EDIT:
In your case, it will be something like this:
NSInteger someInteger = ((Comments *) [self.list objectAtIndex:0]).noofcomm;
NSString someString = [NSString stringWithFormat:#"%d", someInteger];
self.comments2.text = someString;
If it's still not working, FOR SURE the problem is somewhere else, and not with the conversion. Check with property noofcomm has a valid value, check if your label reference is ok (test with a random value before the conversion), and somethings like that.
You need to build an NSString
int someInteger = 10;
NSString *someString = [[NSString alloc] initWithFormat:#"%d", someInteger];
You can use something like [NSString string_from_int:42] in LCategory since 0.1.3: https://github.com/superarts/LCategory
_lbl_yourLabel.text=[NSString stringWithFormat:#"%d",[[dic valueForKey:#"your integer value"] intValue]];
On the top left is your label named "yourLabel" , "dic" is your json response dictionary where all the data is coming in key value terms, "your integer value" is the key for which the value will be assign to the label "yourLabel", we have taken intValue because we cannot assign integer value directly to the label.
or you also can try below:
int anyInteger = 13;
NSString *yourString = [[NSString alloc] initWithFormat:#"%d", anyInteger];
self.yourLabel.text = yourString;

Resources