GoTo to a label in another function - objective-c

i need to do like this:
-(void)function1{
goto start;
}
-(void)function2{
//some code
start://i need to get in here exactly, [self function2] oblige me to execute the function2 from the beginning
//some code..
}
Seems i can not, what can i do instead? thanx in advance.
EDIT: here is my actual code:
-(void)viewWillAppear:(BOOL)animated{
if (sqlite3_open(dbpath, &contactDB) == SQLITE_OK)
{
NSString *querySQL = [NSString stringWithFormat:
#"Select quiz,question,p1,p2,p3,num_correct from question where quiz=(select id from quiz where nom = \'%#\' and niveau= \'%i\' and theme=(select id from theme where nom=\'%#\'))",nomPartieQuiz,quiIslam.theGameLevel,quiIslam.themeChoisie];
const char *query_stmt = [querySQL UTF8String];
if (sqlite3_prepare_v2(contactDB,
query_stmt, -1, &statement, NULL) == SQLITE_OK)
{
start://étiquette
while (sqlite3_step(statement) == SQLITE_ROW && !passToNextQuestion)
{
NSString *addressField = [[NSString alloc]
initWithUTF8String:
(const char *) sqlite3_column_text(
statement, 1)];
NSLog(#"%#",addressField);
txtView.text=addressField;
passToNextQuestion=NO;
}
sqlite3_finalize(statement);
}
sqlite3_close(contactDB);
}
}
-(IBAction)clickOnTheButton:(id)sender{
btn1.hidden=YES;
goto start;
}

Try this:
-(void)function1{
[self function2];
}
-(void)function2{
//some code..
}
And, using "gotos" its only allowed in a very very very specifically kind of situations, you should forget about them right now! It goes again any developing principle.

In regards to your edit, put the logic for the start: into it's own method, then call that method from your viewWillAppear and from any other place you need to execute it. Keep in mind you may need to make some variable global so your method can see them, but this is the idea, even if you have to modify the execution.
-(void)sqlStartLogic {
while (sqlite3_step(statement) == SQLITE_ROW && !passToNextQuestion)
{
NSString *addressField = [[NSString alloc]
initWithUTF8String:
(const char *) sqlite3_column_text(statement, 1)];
NSLog(#"%#",addressField);
txtView.text=addressField;
passToNextQuestion=NO;
}
sqlite3_finalize(statement);
}
-(void)function2 {
[self sqlStartLogic];
}

Related

Sqlite3 step == SQLITE_ROW not working for me

As i am new to Xcode so no idea to fix this issue. Please help me out to figure the actual issue.
Database connection is build up, the query is execute, but I always get the message as : Result not found, after execution the query. :(
- (void)viewDidLoad
{
NSString *MyDirectory;
NSArray *DirectoryPaths;
// Get the documents directory
DirectoryPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
MyDirectory = [DirectoryPaths objectAtIndex:0];
// Build the path to the database file
MyDBPath = [[NSString alloc]initWithString: [MyDirectory stringByAppendingPathComponent:#"mydb.db"]];
//Status.text = MyDBPath;
const char *Database = [MyDBPath UTF8String];
if (sqlite3_open(Database, &MyConnection) == SQLITE_OK)
{
Status.text = #"Build Connection Successfully...!";
}
else
{
Status.text = #"Failed to open database...!";
}
[super viewDidLoad];
}
- (void) Find
{
const char *Database = [MyDBPath UTF8String];
sqlite3_stmt *SQLStatement;
NSString *Query;
if (sqlite3_open(Database, &MyConnection) == SQLITE_OK)
{
Query = [NSString stringWithFormat:#"SELECT EmpName FROM EmpLogin WHERE EmpID=\"%#\"",MyText.text];
if (sqlite3_prepare_v2(MyConnection, [Query UTF8String], 0, &SQLStatement, nil) == SQLITE_OK)
{
while (sqlite3_step(SQLStatement) == SQLITE_ROW)
{
NSString *Name = [[NSString alloc]
initWithUTF8String:(const char *) sqlite3_column_text(SQLStatement, 0)];
TextResult.text = Name;
}
if (TextResult.text.length > 0)
{
Status.text = #"Result found";
}
else
{
NSLog(#"%s", sqlite3_errmsg(MyConnection));
Status.text = #"Result not found";
TextResult.text = #"";
}
sqlite3_finalize(SQLStatement);
}
else
{
//NSString *decode = [[NSString alloc]initWithCString:Query_Stmt encoding:NSUTF8StringEncoding];
//Status.text = decode;
Status.text = #"Query execution Failed...!";
}
sqlite3_close(MyConnection);
}
}
Sqlite3_step(SQLStatement) == SQLITE_ROW __ nor working
Yes i resolved the issue…!!!!
actually i just change the path of the directory to direct to my DB path.
here is my final and working code… anyway thanks #HotLicks,,, #CL. :) :)
This works like a charm … :)
- (void) Find
{
MyDBPath = #"/Users/zaibi/Documents/IOSProjects/mydb.db";
MyDatabase = [MyDBPath UTF8String];
sqlite3_stmt *SQLStatement;
NSString *Query;
//NSString *decode = [[NSString alloc]initWithCString:Database encoding:NSUTF8StringEncoding];
//NSLog(#"%#",decode);
if (sqlite3_open(MyDatabase, &MyConnection) == SQLITE_OK)
{
Query = [NSString stringWithFormat:#"SELECT EmpName FROM EmpLogin WHERE EmpID=\"%#\"",MyText.text];
if (sqlite3_prepare_v2(MyConnection, [Query UTF8String], -1, &SQLStatement, nil) == SQLITE_OK)
{
if (sqlite3_step(SQLStatement) == SQLITE_ROW)
{
NSString *Name = [[NSString alloc]
initWithUTF8String:(const char *) sqlite3_column_text(SQLStatement, 0)];
TextResult.text = Name;
Status.text = #"Result found";
}
else
{
NSLog(#"%s", sqlite3_errmsg(MyConnection));
Status.text = #"Result not found";
TextResult.text = #"";
}
sqlite3_finalize(SQLStatement);
}
else
{
NSLog(#"%s", sqlite3_errmsg(MyConnection));
Status.text = #"Query execution Failed...!";
}
sqlite3_close(MyConnection);
}
}
while this way of accessing the DB is just confusing… :/
NSString *MyDirectory;
NSArray *DirectoryPaths;
// Get the documents directory
DirectoryPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
MyDirectory = [DirectoryPaths objectAtIndex:0];
// Build the path to the database file
MyDBPath = [[NSString alloc]initWithString: [MyDirectory stringByAppendingPathComponent:#"mydb.db"]];
//Status.text = MyDBPath;
Sometimes it helps to read the documentation:
If the nByte argument is less than zero, then zSql is read up to the
first zero terminator. If nByte is non-negative, then it is the
maximum number of bytes read from zSql.

Adding Batch values with an array

I've trying to insert batch data from array in to Sqlite3 for my mobile project.
my code seems to be works fine, but it doesn't insert all data.
PS: I edited my code:
-(BOOL) saveBatchData:(NSArray *)userSourceID userDestID:(NSArray *)userDestID message:(NSArray *)message sentDate:(NSArray *)sentDate
{
const char *dbpath = [databasePath UTF8String];
if (sqlite3_open(dbpath, &database) == SQLITE_OK)
{
for(int i=0; i<[message count]; i++)
{
NSString *insertSQL = [NSString stringWithFormat:#"insert into messages (userSourceID,userDestID, message, sentDate) values (\"%d\",\"%d\", \"%#\",\"%#\")",[[userSourceID objectAtIndex:i] integerValue],[[userDestID objectAtIndex:i] intValue], [message objectAtIndex:i],[sentDate objectAtIndex:i]];
const char *insert_stmt = [insertSQL UTF8String];
sqlite3_prepare_v2(database, insert_stmt,-1, &statement, NULL);
if (sqlite3_step(statement) == SQLITE_DONE)
{
sqlite3_finalize(statement);
return YES;
} else {
NSLog(#"Hata = %s",sqlite3_errmsg(database));
return NO;
}
sqlite3_reset(statement);
}
sqlite3_close(database);
}
return NO;
}
The output seems to be , function just added few rows on 39 elements of array ( i think it's 4 ) . Can someone help me what's my mistake over here ?
Regards...
Your are preparing lots of statements, but execute only the last one.
Move the call to sqlite3_step into the loop.
Please note that you must call sqlite3_finalize for every statement you have prepared, regardless of whether the step suceeded or not.
You must not jump out of the function without calling sqlite3_close.
You must not call sqlite3_reset after the statement has been finalized.

memory leak in sqlite3 in ios

Its location based application and application crash after 5-6
Minutes. When I run the app using performance tools, leaks, I keep
finding that all of my classes leak memory. i am calling this
function second by second. Please properly close my database or
sqlite3. Thanks.
- (void)locationUpdate:(CLLocation *)location {
for (int i=0; i<[arrayAlerts count]; i++) {
Msg=[DatabaseManager GetSelectedMessage:[NSString stringWithFormat:#"select text_msg from TextMsgTemplate where msg_id=%d",ObjAlertInfo.msgID]];
}
in Databasemanger
+(NSString *)GetSelectedMessage:(NSString *)SQL
{
NSString *msg;//=[[[NSString alloc]init] autorelease];
msg=nil;
sqlite3_stmt *dataset=nil;
dataset=[DatabaseManager getMessages:SQL];
while ((sqlite3_step(dataset)==SQLITE_ROW) ) {
msg=[NSString stringWithUTF8String:(char *)sqlite3_column_text(dataset, 0)];
}
sqlite3_finalize(dataset);
dataset = nil;
return msg;
}
+(sqlite3_stmt *)getMessages:(NSString *)SQL
{
sqlite3_stmt *dataset=nil;
sqlite3_stmt *finaldataset=nil;
if (sqlite3_open([[self getdatabasePath] UTF8String], &database) == SQLITE_OK ) {
if (sqlite3_prepare_v2(database, [SQL UTF8String], -1, &dataset, NULL) != SQLITE_OK)
{
NSLog(#"error get message");
return nil;
}else{
finaldataset= dataset;
}
}
sqlite3_close(database);
return finaldataset;
}

SQLite doesn't compile query - Objective C

I have problems with SQLite function sqlite3_prepare_v2, it always returns 1 error code. I'm using SQLite wrapper SQLitemanagerforIOS4. Previously the same error happened without using the wrapper, I switched to it because, despite the statement was encoded in UTF8, the error still happened. I checked the database path with the debugger, and it's correct, so I'm lost...By the way, database is correctly opened and closed.
Here it is the pice of code :
- (NSArray *)getRowsForQuery:(NSString *)sql {
NSMutableArray *resultsArray = [[NSMutableArray alloc] initWithCapacity:1];
if (db == nil) {
[self openDatabase];
}
sqlite3_stmt *statement;
const char *query = [sql UTF8String];
int prepareStatus = sqlite3_prepare_v2(db, query, -1, &statement, NULL);
while (sqlite3_step(statement) == SQLITE_ROW) {
Many thanks for your help.
Here they are the parameters passed to the wrapper object:
- (void)viewDidLoad
{
[super viewDidLoad];
dbManager = [[SQLiteManager alloc] initWithDatabaseNamed:#"XLO.sqlite"];
SArray *provinciaArray = [dbManager getRowsForQuery:[NSString stringWithFormat:#"SELECT provincia FROM provincias;"]];
Thanks!
Peter, here it is:
- (NSError *) openDatabase {
NSError *error = nil;
NSString *databasePath = [self getDatabasePath];
const char *dbpath = [databasePath UTF8String];
#ifdef DEBUG
NSLog(#"SQL result: <%s>", dbpath );
#endif
int result = sqlite3_open(dbpath, &db);
if (result != SQLITE_OK) {
const char *errorMsg = sqlite3_errmsg(db);
NSString *errorStr = [NSString stringWithFormat:#"The database could not be opened: %#",[NSString stringWithCString:errorMsg encoding:NSUTF8StringEncoding]];
error = [self createDBErrorWithDescription:errorStr andCode:kDBFailAtOpen];
}
return error;
}
Many thanks to all!
Because it's saying the database table does not exist, you may not be opening the database # the path that you think you are. Remember that sqlite is passive - it will create a database on first write.
Run the app in the simulator and print out the path. Then go to that path in terminal and use the sqlite cmdline to confirm the db is there and it has the tables.

Send email to multiple recipients with SKPSMTPMessage?

I need to send email in background, so I have to use the library named: SMTP. And the main class I used is: SKPSMTPMessage. The problem is "ccEmail", when I add more than 2 recipients, it can't send email. (that takes too long time to go to delegate methods). It works well with recipient <= 2.
smtpEmail.ccEmail = #"xyz#gmail.com, xyz1#gmail.com, xyz2#gmail.com";
Anyone knows this, please help me. Thanks you so much !
There is my changes in the parseBuffer function:
case kSKPSMTPWaitingFromReply:
{
if ([tmpLine hasPrefix:#"250 "]) {
if (!multipleRcptTo) {
NSMutableString *multipleRcptToString = [NSMutableString string];
[multipleRcptToString appendString:[self formatAddresses:toEmail]];
[multipleRcptToString appendString:[self formatAddresses:ccEmail]];
[multipleRcptToString appendString:[self formatAddresses:bccEmail]];
multipleRcptTo = [[multipleRcptToString componentsSeparatedByString:#"\r\n"] mutableCopy];
[multipleRcptTo removeLastObject];
}
if ([multipleRcptTo count] > 0) {
NSString *rcptTo = [NSString stringWithFormat:#"%#\r\n", [multipleRcptTo objectAtIndex:0]];
[multipleRcptTo removeObjectAtIndex:0];
//DEBUGLOG(#"C: %#", rcptTo);
if (CFWriteStreamWriteFully((CFWriteStreamRef)outputStream, (const uint8_t *)[rcptTo UTF8String], [rcptTo lengthOfBytesUsingEncoding:NSUTF8StringEncoding]) < 0)
{
error = [outputStream streamError];
encounteredError = YES;
}
else
{
[self startShortWatchdog];
}
}
if ([multipleRcptTo count] == 0) {
sendState = kSKPSMTPWaitingToReply;
}
}
break;
}
and add this into header:
NSMutableArray *multipleRcptTo;
EDIT : Also change below method as multipleRcptTo is used as NSMutableString which is local declaration :
- (NSString *)formatAddresses:(NSString *)addresses {
NSCharacterSet *splitSet = [NSCharacterSet characterSetWithCharactersInString:#";,"];
NSMutableString *multipleRcpt = [NSMutableString string];
if ((addresses != nil) && (![addresses isEqualToString:#""])) {
if( [addresses rangeOfString:#";"].location != NSNotFound || [addresses rangeOfString:#","].location != NSNotFound ) {
NSArray *addressParts = [addresses componentsSeparatedByCharactersInSet:splitSet];
for( NSString *address in addressParts ) {
[multipleRcpt appendString:[self formatAnAddress:address]];
}
}
else {
[multipleRcpt appendString:[self formatAnAddress:addresses]];
}
}
return(multipleRcpt);
}
SKPSMTPMessage sends to the SMTP address all at once, and must send one by one.