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
Related
I want to fetch data from sqlite db in objective-c in the form of listArray(like in java android).
Here i have java class models for this
How can i convert these classes into objective c code confused in deceleration(.h) and implementation(.m)
Class 1
public class RecordingList {
public ArrayList<RecordingItem> Items = new ArrayList<RecordingItem>();
}
class 2
public class RecordingItem {
public int ID;
public String RecordingTitle;
public String RecordingSubTitle;
public String RecordingAudioPath;
public String RecordingDuration;
public String RecordingNotePath;
public String Date;
public String Time;
public String PlayListId;
public ArrayList<RecordingAttachments> recordingAttachmentses = new ArrayList<RecordingAttachments>();
}
I have try to get data in objective-c like this
- (NSArray*) getAllNotes
{
const char *dbpath = [databasePath UTF8String];
if (sqlite3_open(dbpath, &database) == SQLITE_OK)
{
NSString *querySQL = [NSString stringWithFormat:
#"SELECT * FROM recordingItem"];
const char *query_stmt = [querySQL UTF8String];
NSMutableArray *resultArray = [[NSMutableArray alloc]init];
if (sqlite3_prepare_v2(database,
query_stmt, -1, &statement, NULL) == SQLITE_OK)
{
if (sqlite3_step(statement) == SQLITE_ROW)
{
NSString *name = [[NSString alloc] initWithUTF8String:
(const char *) sqlite3_column_text(statement, 0)];
[resultArray addObject:name];
NSString *department = [[NSString alloc] initWithUTF8String:
(const char *) sqlite3_column_text(statement, 1)];
[resultArray addObject:department];
NSString *year = [[NSString alloc]initWithUTF8String:
(const char *) sqlite3_column_text(statement, 2)];
[resultArray addObject:year];
return resultArray;
}
else{
NSLog(#"Not found");
return nil;
}
sqlite3_reset(statement);
}
}
return nil;
}
But this is not what i want i want to get data in list of objects how can i do this?
Thanks in Advance
First off it is advisable to start with Objective C basics on your own. After that you'll be able to rewrite your Java classes in a couple of minutes.
What about data fetching, if you don't want to use CoreData (which is recommended and handy, if you target only iOS), then you can use eg. FMDatabase which is easier to use and hides all the native stuff you wrote here.
One more notice: you put name, department, year one after another in an array, create an ObjC #interface which will hold all the data:
#interface Data : NSObject
#property (nonatomic, strong) NSString *name;
#property (nonatomic, strong) NSString *department;
#property (nonatomic, strong) NSString *year;
#end
and use it like that:
NSMutableArray *resultArray = [NSMutableArray new];
// fetch ...
Data *data = [[Data alloc] init];
data.name = [[NSString alloc] initWithUTF8String:(const char *) sqlite3_column_text(statement, 0)];
// other fields ...
[resultArray addObject:data];
One more notice: you can now create parametric arrays just like in Java.
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;
}
Novice Programmer - do this for fun and learning..
I am trying to populate 2 UIPickerView's with data from a SQLite query
Every time I run this, I get this error:
-[__NSArrayI length]: unrecognized selector sent to instance
What I'm trying to do is simple, and shouldn't be this painful a problem. Can you please review, and tell me what may be causing the error?
Please note, I have stripped a lot of the "fluffy" code out for the display elements - I am aware that none of this code is causing any of the issues..
FuelEdit.m
#import "FuelEdit.h"
#import "DBManager.h"
#interface FuelEdit ()
#property (nonatomic, strong) DBManager *dbManager;
#end
#implementation FuelEdit
#synthesize regoPicker;
#synthesize locationPicker;
#synthesize datePicker;
- (void)viewDidLoad
{
self.dbManager = [[DBManager alloc] initWithDatabaseFilename:#"fuel.sql"];
regoPicker.delegate = self;
regoPicker.dataSource = self;
locationPicker.delegate = self;
locationPicker.dataSource = self;
[regoPicker setShowsSelectionIndicator:YES];
}
- (void)viewWillAppear{
}
- (NSInteger)numberOfComponentsInPickerView: (UIPickerView *)pickerView
{
if (pickerView == regoPicker) {
return 1;
} else if (pickerView == locationPicker) {
return 1;
} else {
return 1;
}
}
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
if (pickerView == regoPicker) {
NSString *query = [NSString stringWithFormat:#"SELECT * FROM aircraft"];
// Load the relevant data.
NSArray *results = [[NSArray alloc] initWithArray:[self.dbManager loadDataFromDB:query]];
return results.count;
} else if (pickerView == locationPicker) {
NSString *query = [NSString stringWithFormat:#"SELECT * FROM location"];
// Load the relevant data.
NSArray *results = [[NSArray alloc] initWithArray:[self.dbManager loadDataFromDB:query]];
return results.count;
} else {
return 1;
}
}
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
if (pickerView == regoPicker) {
NSString *query = [NSString stringWithFormat:#"SELECT acrego FROM aircraft"];
// Load the relevant data.
NSArray *results = [[NSArray alloc] initWithArray:[self.dbManager loadDataFromDB:query]];
if (results !=nil) {
return [results objectAtIndex:row];
} else {
return nil;
}
} else if (pickerView == locationPicker) {
NSString *query = [NSString stringWithFormat:#"SELECT locname FROM location"];
// Load the relevant data.
NSArray *results = [[NSArray alloc] initWithArray:[self.dbManager loadDataFromDB:query]];
if (results != nil) {
return [results objectAtIndex:row];
} else {
return nil;
}
} else {
return 0;
}
}
FuelEdit.h
#import <UIKit/UIKit.h>
#protocol FuelEditDelegate
#end
#interface FuelEdit : UITableViewController <UITableViewDelegate, UITableViewDataSource, UIPickerViewDataSource, UIPickerViewDelegate>
#property (nonatomic, strong) id<FuelEditDelegate> delegate;
#property (weak, nonatomic) IBOutlet UIPickerView *regoPicker;
#property (weak, nonatomic) IBOutlet UIDatePicker *datePicker;
#property (weak, nonatomic) IBOutlet UIPickerView *locationPicker;
#end
DBManager.m:
#import <Foundation/Foundation.h>
#import "DBManager.h"
#import <sqlite3.h>
#interface DBManager()
#property (nonatomic, strong) NSString *documentsDirectory;
#property (nonatomic, strong) NSString *databaseFilename;
#property (nonatomic, strong) NSMutableArray *arrResults;
-(void)copyDatabaseIntoDocumentsDirectory;
-(void)runQuery:(const char *)query isQueryExecutable:(BOOL)queryExecutable;
#end
#implementation DBManager
-(instancetype)initWithDatabaseFilename:(NSString *)system{
self = [super init];
if (self) {
// Set the documents directory path to the documentsDirectory property.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
self.documentsDirectory = [paths objectAtIndex:0];
// Keep the database filename.
self.databaseFilename = system;
// Copy the database file into the documents directory if necessary.
[self copyDatabaseIntoDocumentsDirectory];
}
return self;
}
-(void)copyDatabaseIntoDocumentsDirectory{
// Check if the database file exists in the documents directory.
NSString *destinationPath = [self.documentsDirectory stringByAppendingPathComponent:self.databaseFilename];
if (![[NSFileManager defaultManager] fileExistsAtPath:destinationPath]) {
// The database file does not exist in the documents directory, so copy it from the main bundle now.
NSString *sourcePath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:self.databaseFilename];
NSError *error;
[[NSFileManager defaultManager] copyItemAtPath:sourcePath toPath:destinationPath error:&error];
// Check if any error occurred during copying and display it.
if (error != nil) {
NSLog(#"Copy Database Error: %#", [error localizedDescription]);
}
}
}
-(void)runQuery:(const char *)query isQueryExecutable:(BOOL)queryExecutable{
// Create a sqlite object.
sqlite3 *sqlite3Database;
// Set the database file path.
NSString *databasePath = [self.documentsDirectory stringByAppendingPathComponent:self.databaseFilename];
// Initialize the results array.
if (self.arrResults != nil) {
[self.arrResults removeAllObjects];
self.arrResults = nil;
}
self.arrResults = [[NSMutableArray alloc] init];
// Initialize the column names array.
if (self.arrColumnNames != nil) {
[self.arrColumnNames removeAllObjects];
self.arrColumnNames = nil;
}
self.arrColumnNames = [[NSMutableArray alloc] init];
// Open the database.
BOOL openDatabaseResult = sqlite3_open([databasePath UTF8String], &sqlite3Database);
if(openDatabaseResult == SQLITE_OK) {
// Declare a sqlite3_stmt object in which will be stored the query after having been compiled into a SQLite statement.
sqlite3_stmt *compiledStatement;
// Load all data from database to memory.
BOOL prepareStatementResult = sqlite3_prepare_v2(sqlite3Database, query, -1, &compiledStatement, NULL);
if(prepareStatementResult == SQLITE_OK) {
// Check if the query is non-executable.
if (!queryExecutable){
// In this case data must be loaded from the database.
// Declare an array to keep the data for each fetched row.
NSMutableArray *arrDataRow;
// Loop through the results and add them to the results array row by row.
while(sqlite3_step(compiledStatement) == SQLITE_ROW) {
// Initialize the mutable array that will contain the data of a fetched row.
arrDataRow = [[NSMutableArray alloc] init];
// Get the total number of columns.
int totalColumns = sqlite3_column_count(compiledStatement);
// Go through all columns and fetch each column data.
for (int i=0; i<totalColumns; i++){
// Convert the column data to text (characters).
char *dbDataAsChars = (char *)sqlite3_column_text(compiledStatement, i);
// If there are contents in the currenct column (field) then add them to the current row array.
if (dbDataAsChars != NULL) {
// Convert the characters to string.
[arrDataRow addObject:[NSString stringWithUTF8String:dbDataAsChars]];
}
// Keep the current column name.
if (self.arrColumnNames.count != totalColumns) {
dbDataAsChars = (char *)sqlite3_column_name(compiledStatement, i);
[self.arrColumnNames addObject:[NSString stringWithUTF8String:dbDataAsChars]];
}
}
// Store each fetched data row in the results array, but first check if there is actually data.
if (arrDataRow.count > 0) {
[self.arrResults addObject:arrDataRow];
}
}
}
else {
// This is the case of an executable query (insert, update, ...).
// Execute the query.
//BOOL executeQueryResults = sqlite3_step(compiledStatement);
//if (executeQueryResults == SQLITE_DONE) {
if (sqlite3_step(compiledStatement)) {
// Keep the affected rows.
self.affectedRows = sqlite3_changes(sqlite3Database);
// Keep the last inserted row ID.
self.lastInsertedRowID = sqlite3_last_insert_rowid(sqlite3Database);
}
else {
// If could not execute the query show the error message on the debugger.
NSLog(#"DB Error: %s", sqlite3_errmsg(sqlite3Database));
}
}
}
else {
// In the database cannot be opened then show the error message on the debugger.
NSLog(#"%s", sqlite3_errmsg(sqlite3Database));
}
// Release the compiled statement from memory.
sqlite3_finalize(compiledStatement);
}
// Close the database.
sqlite3_close(sqlite3Database);
}
-(NSArray *)loadDataFromDB:(NSString *)query{
// Run the query and indicate that is not executable.
// The query string is converted to a char* object.
[self runQuery:[query UTF8String] isQueryExecutable:NO];
// Returned the loaded results.
return (NSArray *)self.arrResults;
}
-(void)executeQuery:(NSString *)query{
// Run the query and indicate that is executable.
[self runQuery:[query UTF8String] isQueryExecutable:YES];
}
#end
Make sure your results contain only one array it must not be list of array. I am feeling like when you are doing this
return [results objectAtIndex:row];
it is returning a array instead of returning a string. May be your results contain list of arrays. Please verify this thing.
Error is for the unrecognized selector. It means you are calling length function for an array or returning Array instead of string in any of the method.
I have checked your code.Please check in following section:
NSArray *results = [[NSArray alloc] initWithArray:[self.dbManager loadDataFromDB:query]];
if (results !=nil) {
return [results objectAtIndex:row];
}
I think [results objectAtIndex:row] is returning a array instead of the string.
Please let me know the results...
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.
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;