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;
Related
I am a beginner to iOS. I am trying to access/read the sqlite DB from within my App and for which I used a model class where I initialize a custom initializer. Values are getting successfully in custom initializers but my issue is that the values are not populating in modal class object.
Here is the code which I implement:
// ViewController.m
{
[self thehadithList];
sqlite3 *database;
NSString *databasePath;
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [documentPaths objectAtIndex:0];
databasePath = [documentsDir stringByAppendingPathComponent:#"hadithQudsi.db"];
if(sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK) {
const char *sqlStatement = "select * from hadith";
sqlite3_stmt *compiledStatement;
if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK) {
while(sqlite3_step(compiledStatement) == SQLITE_ROW) {
NSInteger aID = sqlite3_column_int (compiledStatement, 0);
NSString *aHA = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 1)];
NSString *aHE = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 2)];
NSString *aRA = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 3)];
NSString *aRE = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 4)];
NSInteger aF = sqlite3_column_int (compiledStatement, 5);
Hadith *hadith1 = [[Hadith alloc] initWithId:aID hadith_ar:aHA hadith_en:aHE ref_ar:aRA ref_en:aRE favourites:aF];
[thehadithList addObject:hadith1]; **// **** Here in Custom class object, values are not been getting **** //**
}
}
sqlite3_finalize(compiledStatement);
}
sqlite3_close(database);
}
// Hadith.h (this is Modal Class)
#property (nonatomic,readwrite) NSInteger _id;
#property (nonatomic,strong) NSString *hadith_ar;
#property (nonatomic,strong) NSString *hadith_en;
#property (nonatomic,strong) NSString *ref_ar;
#property (nonatomic,strong) NSString *ref_en;
#property (nonatomic,readwrite) NSInteger favourites;
-(id)initWithId:(NSInteger)ID hadith_ar:(NSString *)ha hadith_en:(NSString *)he ref_ar:(NSString *)ra ref_en:(NSString *)re favourites:(NSInteger)f;
// Hadith.m
#synthesize _id,hadith_ar,hadith_en,ref_ar,ref_en,favourites;
-(id)initWithId:(NSInteger)ID hadith_ar:(NSString *)ha hadith_en:(NSString *)he ref_ar:(NSString *)ra ref_en:(NSString *)re favourites:(NSInteger )f
{
if (self = [super init]) {
self._id = ID;
self.hadith_ar = ha;
self.hadith_en = he;
self.ref_ar = ra;
self.ref_en = re;
self.favourites = f;
}
return self;
}
What I'm doing wrong? Is there anything missing? Any help would be greatly appreciated. Thanks in advance :)
try this
-(id)initWithId:(NSInteger)ID hadith_ar:(NSString *)ha hadith_en:(NSString *)he ref_ar:(NSString *)ra ref_en:(NSString *)re favourites:(NSInteger )f
{
self = [super init];
self._id = ID;
self.hadith_ar = ha;
self.hadith_en = he;
self.ref_ar = ra;
self.ref_en = re;
self.favourites = f;
return self;
}
Try this one
-(id)initWithId:(NSInteger)ID hadith_ar:(NSString *)ha hadith_en:(NSString *)he ref_ar:(NSString *)ra ref_en:(NSString *)re favourites:(NSInteger )f
{
self = [super init];
__id = ID;
_hadith_ar = ha;
_hadith_en = he;
_ref_ar = ra;
_ref_en = re;
_favourites = f;
return self;
}
So I have a custom TVShow object that has some base fields like id, showName, airDate etc. which are all either NSStrings or NSIntegers and I am attempting to create a bunch of these objects via some data I have gotten from an API online.
So I loop through my NSArray of JSON data and create a TVShow object for each response:
TVShow *show = [[TVShow alloc] initWithData:[NSJSONSerialization JSONObjectWithData:data options:0 error:&error]];
[self.showArray addObject:show];
However, only 7 of these ever get created and then any code below this just ceases to run. I have a NSLog(#"Added"); printing after I create the show and it only gets called 6 times. If I add breakpoints after any of this code, they never get called. I'm not sure what's going on but it must be something to do with how I have set up my TVShow object?
It currently looks like:
#import <UIKit/UIKit.h>
#import <Foundation/Foundation.h>
#interface TVShow : NSObject
#property NSInteger showID;
#property NSString *showName;
#property NSString *airDate;
#property double rating;
#property NSString *imageUrl;
#property NSString *showSummary;
#property NSString *episodeSummary;
#property NSInteger season;
#property NSInteger episode;
- (id)initWithData:(NSDictionary *)data;
#end
and the .m file:
#import <UIKit/UIKit.h>
#import "TVShow.h"
#implementation TVShow
- (id)initWithData:(NSDictionary*)data {
self = [super init];
if(self) {
[self buildObjectFromData:data];
}
return self;
}
-(void)buildObjectFromData:(NSDictionary*)data {
NSDictionary *dict = [data objectForKey:#"_embedded"];
NSDictionary *dict2 = [dict objectForKey:#"nextepisode"];
NSDictionary *dict3 = [data objectForKey:#"image"];
NSString *airDate = [dict2 valueForKey:#"airstamp"];
NSInteger season = [[dict2 valueForKey:#"season"] integerValue];
NSInteger episode = [[dict2 valueForKey:#"episode"] integerValue];
NSString *episodeSummary = [dict2 valueForKey:#"summary"];
NSString *showName = [data valueForKey:#"name"];
NSString *showSummary = [data valueForKey:#"summary"];
NSString *imageUrl = [dict3 valueForKey:#"medium"];
NSInteger showID = [[data valueForKey:#"id"] integerValue];
self.airDate = airDate;
self.showName = showName;
self.season = season;
self.episode = episode;
self.showSummary = [self stringByStrippingHTML:showSummary];
self.episodeSummary = [self stringByStrippingHTML:episodeSummary];
self.imageUrl = imageUrl;
self.showID = showID;
}
-(NSString *) stringByStrippingHTML:(NSString*)string {
NSRange r;
NSString *s = string;
while ((r = [s rangeOfString:#"<[^>]+>" options:NSRegularExpressionSearch]).location != NSNotFound)
s = [s stringByReplacingCharactersInRange:r withString:#""];
return s;
}
#end
If I create the object as just: [[TVShow alloc] init]; everything works fine, so it must be something wrong with this model is what I'm thinking. I'm unsure of what to try next, but any help would be greatly appreciated here.
Turns out there were cases that casued:
-(NSString *) stringByStrippingHTML:(NSString*)string {
NSRange r;
NSString *s = string;
while ((r = [s rangeOfString:#"<[^>]+>" options:NSRegularExpressionSearch]).location != NSNotFound)
s = [s stringByReplacingCharactersInRange:r withString:#""];
return s;
}
to go into infinite loops. Removing this snippet fixed the freeze.
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.
so I've got a barcode scanning app that is supposed to read the barcode, match it up with an entry in a database, and display all other information about the entry.
I'm using a single file DB called trackeddb.sqlite, which was created using terminal and sqlite3 commands. It houses two tables, one for static information about products (each part number is unique and has its own entry) for filling out a 'first scan' entry, and a second table which will house the same product information, but also barcodes. The second table allows the user to store multiple products of the same part number and specs, but using a barcode to create unique entries.
My issue is, when the barcode scans, it's supposed to display information stored in the second table (if the barcode matches). The code is sound, but when I run my barcode through (after an entry is in the second table) it displays no data other than preset text. I've racked my brain over this and I can't figure it out, but I think it may have to do with how I'm referencing my database.
Thanks for your time!
What I am greeted with when I scan the barcodes
This is the sqlite DB
PasteBin link to sqlite db and schema
The database is called from this method
- (id)init {
if ((self = [super init])) {
NSString* sqLiteDb = [[NSBundle mainBundle] pathForResource:#"trackeddb" ofType:#"sqlite"];
if (sqlite3_open([sqLiteDb UTF8String], &_database) != SQLITE_OK) {
NSLog(#"Failed to open database");
}
}
return self;
}
Here are the main portions of my code, the barcode scanner works perfectly so I won't bother posting that bit. This is just for the database.
TrackerDatabase.m
//TrackerDatabase.m
#import "TrackerDatabase.h"
#import "TrackedItems.h"
#import "Barcode.h"
#interface TrackerDatabase()
#end
#implementation TrackerDatabase
static TrackerDatabase *_database;
+ (TrackerDatabase*)database {
if (_database == nil) {
_database = [[TrackerDatabase alloc] init];
}
return _database;
}
- (id)init {
if ((self = [super init])) {
NSString* sqLiteDb = [[NSBundle mainBundle] pathForResource:#"trackeddb" ofType:#"sqlite"];
if (sqlite3_open([sqLiteDb UTF8String], &_database) != SQLITE_OK) {
NSLog(#"Failed to open database");
}
}
return self;
}
- (void)dealloc {
sqlite3_close(_database);
}
- (NSArray *)trackedItems:(NSString *)barcode {
NSMutableArray *retval = [[NSMutableArray alloc] init];
NSString *query = #"SELECT * from Tracked WHERE barcode=";
query = [query stringByAppendingString:barcode];
sqlite3_stmt *statement;
if (sqlite3_prepare_v2(_database, [query UTF8String], -1, &statement, nil) == SQLITE_OK) {
while (sqlite3_step(statement) == SQLITE_ROW) {
char *barcodeChars = (char *) sqlite3_column_text(statement, 0);
char *partNumChars = (char *) sqlite3_column_text(statement, 1);
char *descChars = (char *) sqlite3_column_text(statement, 2);
char *colorChars = (char *) sqlite3_column_text(statement, 3);
char *sizeChars = (char *) sqlite3_column_text(statement, 4);
char *leadChars = (char *) sqlite3_column_text(statement, 5);
char *manufacturerChars = (char *) sqlite3_column_text(statement, 6);
NSString *barcode = [[NSString alloc] initWithUTF8String:barcodeChars];
NSString *partNum = [[NSString alloc] initWithUTF8String:partNumChars];
NSString *desc = [[NSString alloc] initWithUTF8String:descChars];
NSString *color = [[NSString alloc] initWithUTF8String:colorChars];
NSString *size = [[NSString alloc] initWithUTF8String:sizeChars];
NSString *lead = [[NSString alloc] initWithUTF8String:leadChars];
NSString *manufacturer = [[NSString alloc] initWithUTF8String:manufacturerChars];
TrackedItems *items = [[TrackedItems alloc] initWithBarcode:barcode partNum:partNum desc:desc
color:color size:size lead:lead manufacturer:manufacturer];
[retval addObject:items];
}
sqlite3_finalize(statement);
}
return retval;
}
#end
TrackerDatabase.h
//TrackerDatabase.h
#import <Foundation/Foundation.h>
#import <sqlite3.h>
#interface TrackerDatabase : NSObject {
sqlite3 *_database;
}
+ (TrackerDatabase*)database;
- (NSArray *)trackedItems:(NSString*)barcode;
#end
TrackedItems.m
#import "TrackedItems.h"
#implementation TrackedItems
#synthesize barcode = _barcode;
#synthesize partNum = _partNum;
#synthesize desc = _desc;
#synthesize color = _color;
#synthesize size = _size;
#synthesize lead = _lead;
#synthesize manufacturer = _manufacturer;
- (id)initWithBarcode:(NSString *)barcode partNum:(NSString *)partNum desc:(NSString *)desc
color:(NSString *)color size:(NSString *)size lead:(NSString *)lead
manufacturer:(NSString *)manufacturer {
if ((self = [super init])) {
self.barcode = barcode;
self.partNum = partNum;
self.desc = desc;
self.color = color;
self.size = size;
self.lead = lead;
self.manufacturer = manufacturer;
}
return self;
}
- (void) dealloc {
self.barcode = nil;
self.partNum = nil;
self.desc = nil;
self.color = nil;
self.size = nil;
self.lead = nil;
self.manufacturer = nil;
}
#end
TrackedItems.h
#import <Foundation/Foundation.h>
#interface TrackedItems : NSObject {
NSString *_barcode;
NSString *_partNum;
NSString *_desc;
NSString *_color;
NSString *_size;
NSString *_lead;
NSString *_manufacturer;
}
#property (nonatomic, copy) NSString *barcode;
#property (nonatomic, copy) NSString *partNum;
#property (nonatomic, copy) NSString *desc;
#property (nonatomic, copy) NSString *color;
#property (nonatomic, copy) NSString *size;
#property (nonatomic, copy) NSString *lead;
#property (nonatomic, copy) NSString *manufacturer;
- (id)initWithBarcode:(NSString *)barcode partNum:(NSString *)partNum desc:(NSString *)desc
color:(NSString *)color size:(NSString *)size lead:(NSString *)lead
manufacturer:(NSString *)manufacturer;
#end
After a quick look it seems the problem might lie in:
NSString *query = #"SELECT * from Tracked WHERE barcode=";
query = [query stringByAppendingString:barcode];
In your table, barcode is declared as TEXT. So you need to use LIKE instead of =.
What your query string looks like:
SELECT * from Tracked WHERE barcode=123123123123
What it should look like:
SELECT * from Tracked WHERE barcode LIKE '123123123'
If you're sure that you get information from sqlite, check if your tableview is correctly.
I suggest use Core Data, is easy to do and its better than sqlite for 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];
}