I have a picker where its values are populated from the database(using NSMutableArray), the problem is that I'm trying to add a NSString value to index 0 of my picker(or of the NSMutableArray) but nothing is showing just a blank space in that position(position 0) and below it the other values from the database are shown like this(assuming its my picker):
------------------------
------------------------
Mouse
------------------------
Keyboard
------------------------
Motherboard
------------------------
this is my code that I use to retrieve the data from the database:
-(NSMutableArray *)getProducts
{
NSMutableArray *products = [[NSMutableArray alloc] init];
Products *all = [[Products alloc]init];
NSString allstring= #"All";
all.all= allstring; // the "all" is a NSString type variable declared in Products class
[products addObject:all];
NSMutableArray *newadditions = [[NSMutableArray alloc]init];
NSMutableIndexSet *indexes =[NSMutableIndexSet indexSetWithIndex:1];
[indexes addIndex:2];
[indexes addIndex:3];
const char* sql = "SELECT ID,Name \
FROM Products";
sqlite3_stmt *statement;
int sqlResult = sqlite3_prepare_v2(database, sql, -1, &statement, NULL);
if(sqlResult == SQLITE_OK)
{
while(sqlite3_step(statement)==SQLITE_ROW)
{
int i=0;
Products *product =[[Products alloc]init];
char*name = (char*)sqlite3_column_text(statement, 1);
product.name = (name)?[NSString stringWithUTF8String:name]: #"";
[newadditions insertObject:product atIndex:i];
i++;
}
[products insertObjects:newadditions atIndexes:indexes];
sqlite3_finalize(statement);
}
else
{
NSLog(#"Problem with the database");
NSLog(#"%d",sqlResult);
}
return products;
}
Any help would be appreciated :)
EDIT:
This is my Products.h
#interface Products : NSObject
{
NSString *name;
NSString *all;
}
#property (strong,nonatomic) NSString *name;
#property (strong,nonatomic) NSString *all;
#end
Products.m:
#import "Products.h"
#implementation Products
#synthesize name;
#synthesize all;
#end
and where I call the picker:
#interface ViewController () <UIPickerViewDataSource, UIPickerViewDelegate>
#property (strong, nonatomic) IBOutlet PRLabel *namesLabel;
#property (strong, nonatomic) UIPickerView* namesPicker;
#property (strong, nonatomic) NSMutableArray *namesAll;
#end
#implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.namesPicker = [[UIPickerView alloc] init];
self.namesPicker.dataSource = self;
self.namesPicker.delegate = self;
self.namesPicker.showsSelectionIndicator = YES;
self.namesLabel.inputView = [self namesPicker];
self.namesLabel.inputAccessoryView = [self accessoryToolbar];
DBAccess *dbAccess = [[DBAccess alloc]init];
self.namesAll = [dbAccess getProducts];
[dbAccess closeDatabase];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
#pragma mark - UIPickerViewDataSource
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
return 1;
}
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
return [self.namesAll count];
}
#pragma mark - UIPickerViewDelegate
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
Products * prod = [self.namesAll objectAtIndex:row];
return prod.type;
}
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
self.namesLabel.text = [self.namesPicker.delegate pickerView:pickerView titleForRow:row forComponent:component];
}
#end
EDIT AGAIN:
the getProducts before I try to add "All" string to first position of array:
-(NSMutableArray *)getProducts
{
NSMutableArray *products = [[NSMutableArray alloc] init];
const char* sql = "SELECT ID,Name \
FROM Products ";
sqlite3_stmt *statement;
int sqlResult = sqlite3_prepare_v2(database, sql, -1, &statement, NULL);
if(sqlResult == SQLITE_OK)
{
while(sqlite3_step(statement)==SQLITE_ROW)
{
Product *product =[[Product alloc]init];
char*name = (char*)sqlite3_column_text(statement, 1);
product.name = (name)?[NSString stringWithUTF8String:name]: #"";
[products addObject:product];
}
NSLog(#"%#",products);
sqlite3_finalize(statement);
}
else
{
NSLog(#"Problem with the database");
NSLog(#"%d",sqlResult);
}
return products;
}
LOG:
2013-07-24 13:49:56.425 just[1401:c07] Opening Database
2013-07-24 13:49:56.433 just[1401:c07] (
All,
"<Product: 0x719f350>",
"<Product: 0x719fcb0>",
"<Product: 0x719ff30>"
)
2013-07-24 13:49:58.053 just[1401:c07] -[__NSCFConstantString name]: unrecognized selector sent to instance 0xd938
2013-07-24 13:49:58.054 just[1401:c07] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFConstantString name]: unrecognized selector sent to instance 0xd938'
*** First throw call stack:
(0x20a1012 0x11aee7e 0x212c4bd 0x2090bbc 0x209094e 0x6a06 0xeb6fc 0xee886 0x1ad8fb 0x1ad9cf 0x1961bb 0x194872 0x19f5d4 0x52e299 0xed27a 0xed10c 0x1432dd 0x11c26b0 0x269dfc0 0x269233c 0x269deaf 0x4a23fe 0x49b798 0x49ca34 0x49e8a2 0x49e931 0x49e97b 0x498117 0x201386 0x200e29 0x2935 0x125cef 0x125f02 0x103d4a 0xf5698 0x1ffcdf9 0x1ffcad0 0x2016bf5 0x2016962 0x2047bb6 0x2046f44 0x2046e1b 0x1ffb7e3 0x1ffb668 0xf2ffc 0x250d 0x2435)
libc++abi.dylib: terminate called throwing an exception
(lldb)
Change all.all to all.name, and t should work.
As a comment, your code is not very readable. The naming of variables is confusing and the use of indexes is scary. There's no need for a newadditions collection if you can do addObject: for each record you read.
The picker cannot show a random object, but a only a string (in its base configuration). Make sure you add the name or some other string attribute of your Products class to the array, (or instruct your picker's datasource to use the right field).
You should really change some names of your classes and variables. If one instance of your class represents a product, the class name should be Product not Products. Also, to use a property name like all is really not intuitive - try to think of something more generic and descriptive.
Also, in your for loop you set i to 0, use it once and then increase it at the end of the loop. Why? Your index set code can also be eliminated.
Related
Getting this error:
'NSInvalidArgumentException', reason: '-[EngineerModel _isNaturallyRTL]: unrecognized selector sent to instance
I've read How to resolve 'unrecognized selector sent to instance'? and others.
Using Xcode 4.5.1 with arc (my first time with arc)
Here's my code, which is based on an earlier non-arc project which works great
database.m
// Models for data
#import "EngineerModel.h"
- (NSArray *)returnEngineers
{
NSMutableArray *retval = [[NSMutableArray alloc] init];
NSString *query = #"SELECT * FROM engineers";
stmt = nil;
if (sqlite3_prepare_v2(_database, [query UTF8String], -1, &stmt, nil) == SQLITE_OK) {
while (sqlite3_step(stmt) == SQLITE_ROW) {
char *engineerIDChr = (char *) sqlite3_column_text(stmt, 0);
char *engineerNameChr = (char *) sqlite3_column_text(stmt, 1);
char *engineerSigFileChr = (char *) sqlite3_column_text(stmt, 2);
char *engineerPhoneChr = (char *) sqlite3_column_text(stmt, 3);
char *engineerEmailChr = (char *) sqlite3_column_text(stmt, 4);
char *engineerRegNoChr = (char *) sqlite3_column_text(stmt, 5);
NSString *engineerID = [[NSString alloc] initWithUTF8String:engineerIDChr];
NSString *engineerName = [[NSString alloc] initWithUTF8String:engineerNameChr];
NSString *engineerSigFile = [[NSString alloc] initWithUTF8String:engineerSigFileChr];
NSString *engineerPhone = [[NSString alloc] initWithUTF8String:engineerPhoneChr];
NSString *engineerEmail = [[NSString alloc] initWithUTF8String:engineerEmailChr];
NSString *engineerRegNo = [[NSString alloc] initWithUTF8String:engineerRegNoChr];
EngineerModel *info = [[EngineerModel alloc] initWithUniqueId:engineerID
engineerName:engineerName
engineerSigFile:engineerSigFile
engineerPhone:engineerPhone
engineerEmail:engineerEmail
engineerRegNo:engineerRegNo];
[retval addObject:info];
}
sqlite3_finalize(stmt);
}
return retval;
}
Database has two entries
And the model
// EngineerModel.h
#import <Foundation/Foundation.h>
#interface EngineerModel : NSObject
{
NSString *_engineerID;
NSString *_engineerName;
NSString *_engineerSigFile;
NSString *_engineerPhone;
NSString *_engineerEmail;
NSString *_engineerRegNo;
}
#property (nonatomic, copy) NSString *engineerID;
#property (nonatomic, copy) NSString *engineerName;
#property (nonatomic, copy) NSString *engineerSigFile;
#property (nonatomic, copy) NSString *engineerPhone;
#property (nonatomic, copy) NSString *engineerEmail;
#property (nonatomic, copy) NSString *engineerRegNo;
- (id)initWithUniqueId:(NSString *)AengineerID
engineerName:(NSString *)AengineerName
engineerSigFile:(NSString *)AengineerSigFile
engineerPhone:(NSString *)AengineerPhone
engineerEmail:(NSString *)AengineerEmail
engineerRegNo:(NSString *)AengineerRegNo;
- (id) init;
#end
// EngineerModel.m
#import "EngineerModel.h"
#interface EngineerModel ()
#end
#implementation EngineerModel
#synthesize engineerID, engineerName, engineerSigFile, engineerPhone, engineerEmail, engineerRegNo;
- (id)initWithUniqueId:(NSString *)AengineerID
engineerName:(NSString *)AengineerName
engineerSigFile:(NSString *)AengineerSigFile
engineerPhone:(NSString *)AengineerPhone
engineerEmail:(NSString *)AengineerEmail
engineerRegNo:(NSString *)AengineerRegNo
{
if ((self = [super init]))
{
self.engineerID = AengineerID;
self.engineerName = AengineerName;
self.engineerSigFile = AengineerSigFile;
self.engineerPhone = AengineerPhone;
self.engineerEmail = AengineerEmail;
self.engineerRegNo = AengineerRegNo;
}
return self;
}
- (id) init {
self = [super init];
return self;
}
#end
Lastly
I've added -ObjC and -all_load to other linker flags
Added #synthesize (I didn't think I had to for arc?)
If I simplify it down to
- (id)initWithId:(NSString *)AengineerID
{
NSLog(#"AengineerID %#",AengineerID);
if ((self = [super init]))
{
self.engineerID = AengineerID;
}
return self;
}
It traces AengineerID then crashes
Any ideas?
_isNaturallyRTL is a private method on NSString. So somehow you've got an EngineerModel instance where some other code is expecting an NSString.
What do you do with that array of EngineerModel objects you return from the returnEngineers method?
And just as a recommendation... using the sqlite3 C API yourself like that is a lesson in frustration. I highly recommend using something like FMDB instead.
Hi, I am trying to get array from StudentDbwithsearchbarViewController class to SearchBarDB class but resultant array not having any data it is giving null Array. Please help me out with this.
thanks in advance
#import <UIKit/UIKit.h>
#interface StudentDbwithsearchbarViewController : UIViewController<UITableViewDelegate,UITableViewDataSource> {
IBOutlet UITextField *txtMarks,*txtSname;
IBOutlet UITableView *tableStudents;
NSMutableArray *arrStudents;
}
#property(nonatomic,retain) NSMutableArray *arrStudents;
-(IBAction)saveStudentDetails;
-(IBAction)gotoSearchpage;
#end
#implementation StudentDbwithsearchbarViewController
#synthesize arrStudents;
- (void)viewDidLoad {
[super viewDidLoad];
arrStudents = [[DbStudent getStudentRecords]retain];
NSLog(#"%#",arrStudents);
NSLog(#"%d",[arrStudents retainCount]);
}
#import "DbStudent.h"
+(NSMutableArray*)getStudentRecords{
NSArray *arrDocPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *strDestPath = [NSString stringWithFormat:#"%#/Student5.sqlite",[arrDocPath objectAtIndex:0]];
NSMutableArray *arrStudents = [[NSMutableArray alloc]init];
sqlite3 *db;
if(sqlite3_open([strDestPath UTF8String], &db)==SQLITE_OK)
{
NSString *query = #"SELECT * FROM Student";
void* v;
char* err_msg;
sqlite3_stmt *studentStmt;
if(sqlite3_prepare_v2(db, [query UTF8String], -1, &studentStmt, &err_msg)==SQLITE_OK)
{
while (sqlite3_step(studentStmt)==SQLITE_ROW) {
int sno = sqlite3_column_int(studentStmt, 0);
NSString *sname = [NSString stringWithUTF8String: sqlite3_column_text(studentStmt, 1)];
float marks = sqlite3_column_double(studentStmt, 2);
Student *st = [[Student alloc]init];
st.Sno = sno;
st.Sname = sname;
st.marks = marks;
[arrStudents addObject:st];
}
}
}
return arrStudents;
}
#import "SearchBarDB.h"
#import"StudentDbwithsearchbarViewController.h"
- (void)viewDidLoad {
[super viewDidLoad];
StudentDbwithsearchbarViewController *sbd = [[StudentDbwithsearchbarViewController alloc]init];
NSLog(#"%d",[sbd.arrStudents retainCount]);
NSLog(#"%#",sbd.arrStudents);
// arrstudentBase = [sbd.arrStudents copy];
arrMatchedString = [[NSMutableArray alloc]init];
}
Lots of potential problems, no definitive answer without a clue as to what you've tried or how you've determined that it failed.
methods should not be prefixed with get; just call it studentRecords or fetchStudentRecords
your memory management code is all over the place; you'll be leaking that array, at the least.
retainCount is useless, don't call it.
writing raw SQL is a waste of time; at least use a wrapper like FMDB or, better yet, move to CoreData
Best guess for failure: the database doesn't exist or the query fails. Have you stepped through the query code?
I've made a container class to store a single tweet. Its initialized by passing in a dictionary object which is a single tweet.
I then store an array of these 'tweets' which I process through to display in a table.
The project is now finished and I am reviewing everything at the moment and I was wondering is there a better way to do this in the future. Is the memory handled correctly. I declare the string member vars with 'copy' and later in the dealloc I use a 'release' rather than just setting them to 'nil'.
Is my init ok or could that be improved?
Tweet.h
#import
#interface Tweet : NSObject
{
NSString * _userName;
NSString * _tweetText;
NSString * _tweetURL;
}
#property (nonatomic, copy) NSString * userName;
#property (nonatomic, copy) NSString * tweetText;
#property (nonatomic, copy) NSString * tweetURL;
- (id) initWithDict:(NSDictionary *)productsDictionary;
#end
Tweet.m
#implementation Tweet
#synthesize userName = _userName;
#synthesize tweetText = _tweetText;
#synthesize tweetURL = _tweetURL;
- (id) initWithDict:(NSDictionary *)productsDictionary
{
NSDictionary *aDict = [productsDictionary objectForKey:#"user"];
self.userName = [aDict objectForKey:#"screen_name"];
self.tweetText = [productsDictionary objectForKey:#"text"];
NSRange match;
match = [self.tweetText rangeOfString: #"http://"];
if (match.location != NSNotFound)
{
NSString *substring = [self.tweetText substringFromIndex:match.location];
NSRange match2 = [substring rangeOfString: #" "];
if (match2.location == NSNotFound)
{
self.tweetURL = substring;
}
else
{
self.tweetURL = [substring substringToIndex:match2.location];
}
}
else
{
self.tweetURL = nil;
}
return self;
}
-(void) dealloc
{
[self.tweetText release];
[self.tweetURL release];
[self.userName release];
[super dealloc];
}
#end
Many Thanks,
Code
At first sight, I see no inherent flaws here. That looks fine. I would prefer to do:
-(void) dealloc
{
[_tweetText release];
[_tweetURL release];
[_userName release];
[super dealloc];
}
But what you do is good as well.
I am doing an alarm app for iOS, but I am a bit confused in taking data from different classes and save them to db in controller class.
for taking name, I have Name class, for taking time I have Time Class, for taking ringtone type, I have Ringtone class, so I am taking different values for one alarmTable(sqlite table) and saving them to db on save button which is in Controller.
I thought to take from every class and save them to delegate variables, and then fetch in controller class, is it almost successful, but having trouble in saving again default values,
Can anyone guide me that what is logic behind this?
These are variables in appDelegate
NSString *name;
NSString *time;
NSString *repeat;
NSString *sound;
NSString *snooz;
NSString *soundFade;
NSString *volume;
NSString *vibrate;
NSString *soundName;
This is way of getting values from appDelegates
-(NSString *) getName {
return name;
}
-(NSString *) getTime {
return time;
}
-(NSString *) getRepeat {
return repeat;
}
-(NSString *) getSound {
return sound;
}
-(NSString *) getSnooz {
return snooz;
}
-(NSString *) getSoundFade {
return soundFade;
}
-(NSString *) getVolume {
return volume;
}
-(NSString *) getVibrate {
return vibrate;
}
and when I do assign values to these delegate variables, I do write in different classes are below
AlarmProjectAppDelegate *delegate = (AlarmProjectAppDelegate *)[[UIApplication sharedApplication] delegate];
[delegate setName:name_textField.text];//name_textField contain alarmname
and I do like this before adding to Database
AlarmProjectAppDelegate *delegate = (AlarmProjectAppDelegate *)[[UIApplication sharedApplication] delegate];
//data for databas for new alarm start
NSString *name=[delegate getName];
NSString *time=[delegate getTime];
NSString *repeat=[delegate getRepeat];
NSString *sound=[delegate getSound];
NSString *snooz=[delegate getSnooz];
NSString *soundFade=delegate.soundFade;
NSString *volume=[delegate getVolume];
NSString *vibrate= [delegate getVibrate];
To make it simpler, you have to do is...
1. Create a separate class for individual table and declare all columns of table as variable in it.
2. Whenever you want to insert into any table, just create an instance of that table class and set all the variables.
3.Finally, pass that instance to your insert query as a parameter and get values from that.
For example...Create a class for Alarm table as below.
For master class, I'm modifying partial code. Assume it with name, time and repeat class.
In Alarm.h
#import <Foundation/Foundation.h>
#interface Alarm : NSObject {
name *objName;
time *objTime;
repeat *objRepeat;
}
// sample code for master class.
#property (nonatomic, retain) NSString *objName;
#property (nonatomic, retain) NSString *objTme;
#property (nonatomic, retain) NSString *objRepeat;
#end
In Alarm.m
#import "Alarm.h"
#implementation Alarm
#synthesize objName;
#synthesize objTime;
#synthesize objRepeat;
#end
Now, call your insert query as given below...
- (void) InsertAlarmData : (Alarm*)objAlarm
{
name *objName = objAlarm.objName;
time *objTime = objAlarm.objTime;
repeat *objRepeat = objAlarm.objRepeat;
NSString *query = [NSString stringWithFormat:#"INSERT into Alarm(name, time, repeat) values ('%#','%#','%#')", objAlarm.objName, objAlarm.objTime, objAlarm.objRepeat];
const char *sql = [query cStringUsingEncoding:NSUTF8StringEncoding];
if (sqlite3_open([databasePath UTF8String], &dbaseConnection) == SQLITE_OK)
{
if (sqlite3_prepare_v2(masterDBase, sql, -1, &hydrate_statement, NULL) == SQLITE_OK)
{
int success = sqlite3_step(hydrate_statement);
sqlite3_reset(hydrate_statement);
if (success != SQLITE_DONE)
{
UIAlertView *alert=[[UIAlertView alloc]initWithTitle:#"Database operation is not successful.." message:#" " delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil,nil];
[alert show];
[alert release];
NSLog(#"Error: failed to excecute query domain with message '%s'.", sqlite3_errmsg(masterDB));
}
}
else
{
NSAssert1(0, #"Error while creating add statement. '%s'", sqlite3_errmsg (masterDB));
}
sqlite3_reset(hydrate_statement);
sqlite3_finalize(hydrate_statement);
}
}
To set values in Alarm class...
name *objName = [[name alloc] init];
objName.name = #"ABC";
time *objTime = [[time alloc] init];
objTime.time = #"5 AM";
repeat *objRepeat = [[repeat alloc] init];
objRepeat.repeat = #"After 5 mins";
Alarm *objAlarm = [[Alarm alloc] init];
objAlarm.objName = objName;
objAlarm.objTime = objTime;
objAlarm.objRepeat = objRepeat;
[self InsertAlarmData:objAlarm];
Hope, you are getting my point exactly now.
if I try and reun the code below I get an EXE_bad_access message on [categoryList count]
NSMutableArray *categoryList = [[CategoryItem alloc] getAll];
NSLog(#"number of items is %#", [categoryList count]);
The class is below
#import "CategoryItem.h"
#import "SQLite.h"
#interface CategoryItem : NSObject {
NSInteger ID;
NSInteger SortOrder;
NSString *Name;
NSString *ShoppingImage;
}
#property (nonatomic, nonatomic) NSInteger SortOrder;
#property (nonatomic, retain) NSString * Name;
#property (nonatomic, retain) NSString * ShoppingImage;
#property (nonatomic, nonatomic) NSInteger ID;
- (id)initWithObject:(NSInteger)itemID;
-(NSMutableArray *)getAll;
#end
#implementation CategoryItem
#synthesize ShoppingImage;
#synthesize Name;
#synthesize ID;
#synthesize SortOrder;
- (id)initWithObject:(NSInteger)itemID {
if ((self = [super init])) {
sqlite3 *database;
// Open the database. The database was prepared outside the application.
if (sqlite3_open([[SQLite fullFilePath] UTF8String], &database) == SQLITE_OK) {
// Get the primary key for all books.
const char *sql = "SELECT ID, Name, ShoppingImage, SortOrder FROM CategoryItem WHERE ID =?";
sqlite3_stmt *statement;
// Preparing a statement compiles the SQL query into a byte-code program in the SQLite library.
// The third parameter is either the length of the SQL string or -1 to read up to the first null terminator.
if (sqlite3_prepare_v2(database, sql, -1, &statement, NULL) == SQLITE_OK) {
// We "step" through the results - once for each row.
sqlite3_bind_int(statement, 1, itemID);
while (sqlite3_step(statement) == SQLITE_ROW) {
// The second parameter indicates the column index into the result set.
self.ID = itemID;
self.Name = [NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 1)];
self.ShoppingImage = [NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 2)];
self.SortOrder = sqlite3_column_int(statement, 3);
}
}
// "Finalize" the statement - releases the resources associated with the statement.
sqlite3_finalize(statement);
} else {
// Even though the open failed, call close to properly clean up resources.
sqlite3_close(database);
NSLog(#"Failed to open database with message '%s'.", sqlite3_errmsg(database));
// Additional error handling, as appropriate...
}
}
return self;
}
-(NSMutableArray*)getAll{
NSMutableArray *listArray = [[[NSMutableArray alloc] init] autorelease];
sqlite3 *database;
// Open the database. The database was prepared outside the application.
if (sqlite3_open([[SQLite fullFilePath] UTF8String], &database) == SQLITE_OK) {
// Get the primary key for all books.
const char *sql = "SELECT ID, Name, ShoppingImage, SortOrder FROM CategoryItem ORDER BY SortOrder";
sqlite3_stmt *statement;
// Preparing a statement compiles the SQL query into a byte-code program in the SQLite library.
// The third parameter is either the length of the SQL string or -1 to read up to the first null terminator.
if (sqlite3_prepare_v2(database, sql, -1, &statement, NULL) == SQLITE_OK)
{
// We "step" through the results - once for each row.
while (sqlite3_step(statement) == SQLITE_ROW)
{
// The second parameter indicates the column index into the result set.
CategoryItem *categoryItem = [[CategoryItem alloc] init];
categoryItem.ID = sqlite3_column_int(statement, 0);
categoryItem.Name = [NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 1)];
categoryItem.ShoppingImage = [NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 2)];
categoryItem.SortOrder = sqlite3_column_int(statement, 3);
[listArray addObject:categoryItem];
[categoryItem release];
categoryItem = nil;
}
}else{
printf( "could not prepare statemnt: %s\n", sqlite3_errmsg(database) );
}
// "Finalize" the statement - releases the resources associated with the statement.
sqlite3_finalize(statement);
} else {
// Even though the open failed, call close to properly clean up resources.
sqlite3_close(database);
NSLog(#"Failed to open database with message '%s'.", sqlite3_errmsg(database));
// Additional error handling, as appropriate...
}
//NSLog(#"this is the list array count %#", [listArray count]);
return listArray;
}
- (void)dealloc {
[super dealloc];
[Name release];
[ShoppingImage release];
}
#end
It doesn't seem right the way you create your CategoryItem. You are calling allocbut not any init... method. You may want to use the initWithObject method that you have provided in your implementation.
From Apple docs:
It takes two steps to create an object
using Objective-C. You must:
Dynamically allocate memory for the
new object
Initialize the newly
allocated memory to appropriate values
An object isn’t fully functional until
both steps have been completed. Each
step is accomplished by a separate
method but typically in a single line
of code:
id anObject = [[Rectangle alloc]
init];
EDIT:
Beyond the initialization problem, there seems to be a conceptual problem (pointed out by #Terry Wilcox):
Calling the method getAllon an instance does not seem to make sense and therefore should be defined as a class method instead:
+ (NSMutableArray*)getAll;
and should be called like this:
NSMutableArray *categoryList = [CategoryItem getAll];
EDIT 2:
Your log statement does not seem right either. [categoryList count]returns a NSUIntegerand you are trying to print an object with %#. Use %iinstead:
NSLog(#"number of items is %i", [categoryList count]);
This code:
NSMutableArray *categoryList = [[CategoryItem alloc] getAll];
doesn't make sense. If getAll is a class method on CategoryItem, then it should be defined as
+ (NSMutableArray*)getAll;
and you should call it as
NSMutableArray *categoryList = [CategoryItem getAll];
Then categoryList will be an array that you don't own, so you may want to retain it when you get it.