I want to store a custom class MCOIMAPSession object into sqlite3 database. I read about NSKeyedArchiver and trying to use that like below.
- (void) updateImapSessionForAccount :(NSString *) emailAddress :(MCOIMAPSession *)imapSession {
const char *dbpath = [databasePath UTF8String];
//SQLIte Statement
NSString *selettablequery = [NSString stringWithFormat:#"select * from MailBoxInfoDBTable"];
if (sqlite3_open(dbpath, &database) == SQLITE_OK)
{
//if(sqlite3_prepare_v2(database, [selettablequery UTF8String], -1, &statement, NULL) == SQLITE_OK)
if (sqlite3_prepare(database, [selettablequery UTF8String], -1, &statement, NULL) ==SQLITE_OK)
{
// Take an array to store all string.
//NSMutableArray *allRows = [[NSMutableArray alloc] init];
while(sqlite3_step(statement) == SQLITE_ROW)
{
char *emailfield = (char *) sqlite3_column_text(statement,0);
NSString *emailStr = [[NSString alloc] initWithUTF8String: emailfield];
NSLog(#"updateMailMessagesPerAccount: %#", emailStr);
if([emailStr isEqualToString:emailAddress])
{
sqlite3_reset(statement);
NSData *messagesData = [NSKeyedArchiver archivedDataWithRootObject:imapSession];
NSString* stringFromData = [messagesData base64EncodedStringWithOptions:0];
NSString *sqlStr = [NSString stringWithFormat:#"update MailBoxInfoDBTable set imapsession='%#' where emailid='%#'", stringFromData, emailAddress];
const char *updateStatement = [sqlStr UTF8String];
if (sqlite3_prepare(database, updateStatement, -1, &statement, NULL) == SQLITE_OK)
{
if(SQLITE_DONE != sqlite3_step(statement))
NSLog(#"Error while updating. %s", sqlite3_errmsg(database));
sqlite3_finalize(statement);
sqlite3_close(database);
return;
}
else
{
NSLog(#"Error in statement: %s", sqlite3_errmsg(database));
}
}
}
}
sqlite3_finalize(statement);
sqlite3_close(database);
}
}
- (MCOIMAPSession *) retrieveImapSessionForAccount :(NSString *) emailAddress {
MCOIMAPSession *imapsessionObj = nil;
const char *dbpath = [databasePath UTF8String];
//SQLIte Statement
NSString *selettablequery = [NSString stringWithFormat:#"select * from MailBoxInfoDBTable"];
if (sqlite3_open(dbpath, &database) == SQLITE_OK)
{
//if(sqlite3_prepare_v2(database, [selettablequery UTF8String], -1, &statement, NULL) == SQLITE_OK)
if (sqlite3_prepare(database, [selettablequery UTF8String], -1, &statement, NULL) ==SQLITE_OK)
{
// Take an array to store all string.
//NSMutableArray *allRows = [[NSMutableArray alloc] init];
while(sqlite3_step(statement) == SQLITE_ROW)
{
char *emailfield = (char *) sqlite3_column_text(statement, 0);
NSString *emailStr = [[NSString alloc] initWithUTF8String: emailfield];
NSLog(#"retrieveImapSessionForAccount: Email: %#", emailStr);
if([emailStr isEqualToString:emailAddress])
{
//const void *bytes = sqlite3_column_blob(statement, 3);
char *emailstring = (char *) sqlite3_column_text(statement, 3);
if (emailstring) {
NSString *messageStr = [[NSString alloc] initWithUTF8String: emailstring];
NSData *data = [[NSData alloc] initWithBase64EncodedString:messageStr options:NSDataBase64DecodingIgnoreUnknownCharacters];
imapsessionObj = [NSKeyedUnarchiver unarchiveObjectWithData:data];
}
}
}
}
sqlite3_finalize(statement);
sqlite3_close(database);
}
return imapsessionObj;
}
I got crash encodeWithCoder unrecognized selector sent to instance when doing NSKeyedArchiver archivedDataWithRootObject:imapSession
Then, I added the below methods in the 3rd party class MCOIMAPSession.mm file
- (void)encodeWithCoder:(NSCoder *)aCoder{
[aCoder encodeObject:self forKey:#"PROPERTY_KEY"];
}
-(id)initWithCoder:(NSCoder *)aDecoder{
if(self = [super init]){
self = [aDecoder decodeObjectForKey:#"PROPERTY_KEY"];
}
return self;
}
UPDATED: I tried the below as well.
#interface MCOIMAPSession : NSObject
....
#end
#interface NSObject (NSCoding)
-(id)initWithCoder:(NSCoder*)decoder;
-(void)encodeWithCoder:(NSCoder*)encoder;
#end
#endif
#implementation MCOIMAPSession
-(id)initWithCoder:(NSCoder *)decoder {
if ((self=[super initWithCoder:decoder])) {
}
return self;
}
#end
#implementation NSObject (NSCoding)
-(id)initWithCoder:(NSCoder*)decoder {
return [self init];
}
-(void)encodeWithCoder:(NSCoder*)encoder {}
#end
HERE IS THE FILE OF MCOIMAPSESSION MCOIMAPSESSION link .. Please let me know how can i add property now?
But, I see still the same crash. Could someone correct me what i'm doing wrong here when storing custom class MCOIMAPSession object in sqlite database?
Your implementation of the NSCoding methods is incorrect. You don't encode/decode self, you encode/decode each property/ivar of self. Something like:
- (void)encodeWithCoder:(NSCoder *)aCoder{
// Replace the following with the class's actual properties
[aCoder encodeObject:self.propertyA forKey:#"propertyA"];
[aCoder encodeObject:self.propertyB forKey:#"propertyB"];
[aCoder encodeObject:self.propertyC forKey:#"propertyC"];
}
-(id)initWithCoder:(NSCoder *)aDecoder{
if(self = [super init]){
// Replace the following with the class's actual properties
_propertyA = [aDecoder decodeObjectForKey:#"propertyA"];
_propertyB = [aDecoder decodeObjectForKey:#"propertyB"];
_propertyC = [aDecoder decodeObjectForKey:#"propertyC"];
}
return self;
}
BTW - your question has nothing at all to do with SQLite. Your question should be narrowed down just to the problem with the encoding/decoding.
You cannot call encodeWithCoder with object self. You have to encode (and decode) each relevant property of the class MCOIMAPSession.
Edit:
For the MCOIMAPSession the NSCoding methods should look like
- (id)initWithCoder:(NSCoder *)decoder
{
self = [super initWithCoder:decoder]
if (self) {
self.hostname = [decoder decodeObjectForKey:#"hostname"];
self.port = [decoder decodeIntegerForKey:#"port"];
self.username = [decoder decodeObjectForKey:#"username"];
self.password = [decoder decodeObjectForKey:#"password"];
// etc
}
return self;
}
-(void)encodeWithCoder:(NSCoder*)encoder
{
[aCoder encodeObject:self.hostname forKey:#"hostname"];
[aCoder encodeInteger:self.port forKey:#"port"];
[aCoder encodeObject:self.username forKey:#"username"];
[aCoder encodeObject:self.password forKey:#"password"];
// etc
}
Add all properties you need. And consider that properties representing instances of other custom classes must be also NSCoding compliant.
Related
I'm following some tutorials from youtube for sqlite crud operations. I have textfields with name, contact and address , when i hit save button it show message in console that data is saved but when i look at database it nothing appears there. My database path is correct and no errors in code but 'm confused why it isn't going. My path code is this,
-(void)copyandpaste{
NSArray *arr1 = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *str1 = [arr1 objectAtIndex:0];
strpath = [str1 stringByAppendingPathComponent:#"personinfo.sqlite"];
if (![[NSFileManager defaultManager]fileExistsAtPath:strpath]) {
NSString *local = [[NSBundle mainBundle]pathForResource:#"personinfo" ofType:#"sqlite"];
[[NSFileManager defaultManager]copyItemAtPath:local toPath:strpath error:nil];
}
NSLog(#"%#",strpath);
}
this method is called in appdelegate.m file,
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
[self copyandpaste];
return YES;
}
I have mad NSObject class for database connection. the connection code is this,
-(id)init{
appdel = (AppDelegate *)[[UIApplication sharedApplication]delegate]; //get all methods in AppDelegate
strmain = appdel.strpath;
return self;
}
-(NSMutableArray *)getalluser:(NSString *)query{
arrdata = [[NSMutableArray alloc]init];
if (sqlite3_open([strmain UTF8String], &(database))==SQLITE_OK) {
sqlite3_stmt *connection;
if (sqlite3_prepare_v2(database, [query UTF8String], -1, &connection, nil)==SQLITE_OK) {
while (sqlite3_step(connection)==SQLITE_ROW) {
NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
NSString *str12 = [[NSString alloc]initWithUTF8String:(char *)sqlite3_column_text(connection, 0)]; //name in first column
NSLog(#"Checking");
NSString *str13 = [[NSString alloc]initWithUTF8String:(char *)sqlite3_column_text(connection, 1)]; //contact in second column
NSString *str14 = [[NSString alloc]initWithUTF8String:(char *)sqlite3_column_text(connection, 2)]; //address in third column
[dic setObject:str12 forKey:#"name"];
[dic setObject:str13 forKey:#"contact"];
[dic setObject:str14 forKey:#"address"];
[arrdata addObject:dic];
}
}
sqlite3_finalize(connection);
}
sqlite3_close(database);
return arrdata;
}
My save button code with query is this,
- (IBAction)btnSave:(id)sender {
NSString *saveDATA=[[NSString alloc]initWithFormat:#"insert into stuInfo values('%#','%#','%#')",txtName,txtContact,txtAddress];
dboperations *db = [[dboperations alloc ]init];
BOOL ds = [db getalluser:saveDATA];
if (ds) {
NSLog(#"Data Saved in database");
}else{
NSLog(#"Data is not Saved in database");
}
}
- (NSString*) saveData:(NSString *)name cont:(NSString *)contacts add:(NSString *)address
{
const char *dbpath = [YOUR_DATA_BASE_PATH UTF8String];
if (sqlite3_open(dbpath, &database) == SQLITE_OK)
{
NSLog(#"=============saveData open==============");
const char * query="insert into YOUR_TABLE_NAME(name,contacts,address) values(?,?,?);";
sqlite3_stmt *inset_statement;
char *errMsg;
if (sqlite3_open(dbpath, &database)!=SQLITE_OK) {
NSLog(#"Error to Open");
return nil;
}
if (sqlite3_prepare_v2(database, query , -1,&inset_statement, NULL) != SQLITE_OK )
{
NSLog(#"%s Prepare failure '%s' (%1d)", __FUNCTION__, sqlite3_errmsg(database), sqlite3_errcode(database));
NSLog(#"Error to Prepare");
return nil;
}
//No of data to insert
sqlite3_bind_text(inset_statement,1,[name UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(inset_statement,2,[contacts UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(inset_statement,3,[address UTF8String], -1, SQLITE_TRANSIENT);
if(sqlite3_step(inset_statement)== SQLITE_DONE)
{
long long lastRowId = sqlite3_last_insert_rowid(database);
NSString *rowId = [NSString stringWithFormat:#"%d", (int)lastRowId];
NSLog(#"Row ID of Last Inserted row %#",rowId);
sqlite3_finalize(inset_statement);
sqlite3_close(database);
NSLog(#"=============saveData Close==============");
return rowId;
}
if (sqlite3_exec(database, query, NULL, NULL, &errMsg)
!= SQLITE_OK)
{
NSLog(#"Failed to Insert msg in message table Error = %s",errMsg);
sqlite3_finalize(inset_statement);
sqlite3_close(database);
NSLog(#"=============saveData Close==============");
return nil;
}
else
{
sqlite3_finalize(inset_statement);
}
}
NSLog(#"=============saveData Close==============");
sqlite3_close(database);
return nil;
}
You are not handling if there are any errors in the SQLite statements you are preparing.
The function will always return true because arrdata is never null
You need to add anelse statements to your
if (sqlite3_prepare_v2(database, [query UTF8String], -1, &connection, nil)==SQLITE_OK)
to show any errors...
NSLog(#"%s",sqlite3_errmsg(database));
- (IBAction)submit:(id)sender {
NSString *sql = [NSString stringWithFormat:#"INSERT INTO employeedetails('employee_name','employee_mailid','employee_username','employee_password')VALUES('%#','%#','%#','%#')",self.textname.text,self.textmailid.text,self.textusername.text,self.textpassword.text];
NSLog(#"%#The inserted values are",sql);
char *err;
if (sqlite3_exec(db,[sql UTF8String], NULL, NULL, &err)!=SQLITE_OK) {
sqlite3_close(db);
NSAssert(0,#"sdsadadsderererwrcould not update the tabel");
}
else{
NSLog(#"nbbbbbbbbbbbbtable updated");
}
}
-(void)selectfn
{
const char *sqlStatement = "SELECT * FROM employeedetails"; // Your Tablename
sqlite3_stmt *compiledStatement;
if(sqlite3_prepare_v2(db, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK)
{
[name removeAllObjects];
while(sqlite3_step(compiledStatement) == SQLITE_ROW)
{
[name addObject:[NSString stringWithFormat:#"%s",(char *) sqlite3_column_text(compiledStatement, 0)]];
NSLog(#"The array value is %#",name);
}
}
sqlite3_finalize(compiledStatement);
sqlite3_close(db);
}
Already I have insert values into table...Now I want to fetch values from the table and want to store one nsarray and display into tableview....help me plz
You can create Model class something like this
Header file
#import "Model.h"
#implementation Model
#synthesize _firstValue ,_secondValue ;
#end
Implementation file
#import <Foundation/Foundation.h>
#interface Model: NSObject
{
NSString *_firstValue ;
NSString *_secondValue ;
}
#property (nonatomic,retain) NSString *_firstValue ;
#property (nonatomic,retain) NSString *_secondValue ;
#end
Now fetching data using below lines...
//Cretae a array to store values
NSMutableArray *retArr = [[NSMutableArray alloc]init];
if ([self dbOpen]) // check db is open
{
const char *sqlStatement = [YOUR_QUERY UTF8String];
sqlite3_stmt *statement;
if( sqlite3_prepare_v2(database, sqlStatement, -1, &statement, NULL) == SQLITE_OK )
{
while( sqlite3_step(statement) == SQLITE_ROW )
{
// used model to fill the set of data
Model *obj = [[Model alloc] init];
obj._firstValue = [NSString stringWithUTF8String:(char *) sqlite3_column_text(statement, 0)];
obj._secondValue = [NSString stringWithUTF8String:(char *) sqlite3_column_text(statement, 1)];
[retArr addObject:obj];
obj = nil;
}
}
else { NSLog( QRY_EXEC_ERROR, sqlite3_errmsg(database) ); } // excute if any error
sqlite3_finalize(statement); // finalizing
sqlite3_close(database); // clossing the DB
}
Finally use retArr which holds your DB values.....
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.
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;
Am i doing this right, because the array is returning a count of 0.
-(NSArray *)getAllFavourites{
NSMutableArray *arrFavourites = [[NSMutableArray alloc] init];
NSString *query = #"SELECT * FROM tbl_favourites;";
sqlite3_stmt *statement;
if (sqlite3_prepare_v2(database, [query UTF8String], -1, &statement, nil) == SQLITE_OK){
while (sqlite3_step(statement) == SQLITE_ROW ){
char *charSymbols = (char *) sqlite3_column_text(statement, 0);
NSString *strFetchedSymbol = [[NSString alloc] initWithUTF8String:charSymbols];
DBClassFavourites *dbClassFav = [[DBClassFavourites alloc] initWithString:strFetchedSymbol];
[arrFavourites addObject:dbClassFav];
}
sqlite3_finalize(statement);
}
NSLog(#"%i",[arrFavourites count]);
return arrFavourites;
}
I also have this class which initialises the variables needed.
#implementation DBClassFavourites
-(id) initWithString:(NSString *)symbol
{
self = [super init];
if (self) {
self.strSymbol = symbol;
}
return self;
}
-(void) dealloc
{
[strSymbol release];
[super dealloc];
}
This is where it all gets called, from my firstviewcontroller init function
#implementation FirstViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
arrFavourites = [[DatabaseManager database] getAllFavourites];
}
You should try to use FMDB wrapper
To find an error in your code you need to post whole database initialization method