Having problems with Array - iphone

SO here's my setup. I have an object called radiostations where I have several strings like callsign, frequency declared and an NSMutableArray called amStationInfo. On my viewcontroller, I access an SQLite database which populates the an array like so...
radiostations.h
#interface radiostations : NSObject {
NSString *format;
NSString *city;
}
#property (nonatomic, retain) NSString *format;
#property (nonatomic, retain) NSString *city;
ViewController.m
radiostations *amStationClass = [[radiostations alloc] init];
NSMutableArray* amStationInfo = [[NSMutableArray alloc] init];
while (sqlite3_step(statement) == SQLITE_ROW)
{
NSString *cityField = [[NSString alloc] initWithUTF8String:
(const char *) sqlite3_column_text(statement, 10)];
NSString *formatField = [[NSString alloc] initWithUTF8String:
(const char *) sqlite3_column_text(statement, 0)];
[amStationInfo addObject:amStationClass];
[amStationClass setCity:cityField];
[amStationClass setFormat:formatField];
}
[tabView reloadData];
sqlite3_finalize(statement);
and then I populate a UITableView
NSString *cityValue = [(radiostations *)[amStationInfo objectAtIndex:indexPath.row] city];
NSString *formatValue = [(radiostations *)[amStationInfo objectAtIndex:indexPath.row] format];
cityLabel.text = cityValue;
formatLabel.text = formatValue;
Initially I was dealing with a few Arrays and this worked just fine. I then changed it so that I was only dealing with one array using a class object and now it's not working. I know the SQLite query and what not works so Im not having any problems with that. It seems as though the array does not get populated.

You are changing the properties of the same radiostations object and adding it over and over again to the array. You need to create a new radiostations object for each row from your sqlite database and add this:
while (...) {
// fetch data as before
radiostations *record = [[radiostations alloc] init];
[record setCity: cityField];
[record setFormat: formatField];
[amStationInfo addObject: record];
[record release];
}
If you are using ARC you need to remove the line [record release];, otherwise it is necessary to avoid leaking those objects.

where did you allocate/init your mutablearray?
something like:
NSMutableArray* amStationInfo = [[NSMutableArray alloc] init];
you need to allocate it once, before to add objects in it

Related

trying to copy array from one class to array but copied array showing null

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?

objective c how to create dictionaries dynamically and refer to them

i need to create and destroy dynamically dictionaries, or arrays,
and have them as instance variables,
so for example, [pseudocode]
*.h
nsmutableDictionary myDictn???
nsstring arrayn ???
how to create an instance dictionarie, and property, that dinamically get created and destroyed?, and how to refer to it?
*.m
n = 0
create container {
myDictn alloc init
n+1
}
other {
myDictn addobject#"data" forKey"myKey"
}
destroy container {
myDictn release
n-1
}
So what intend to show is that i would like to have myDict1, myDict2...
if created,
or destroy them if needed
thanks a lot!
To create dictionaries dynamically & add entries to them you could do this -
NSMutableDictionary *dictResult = [[[NSMutableDictionary alloc] init] retain];
[dictResult setValue:result forKey:#"key"];
Here result can be anything. NSString or NSArray etc. Also using retain retains this object & causes a memory leak if not explicitly released. Instead try to do autorelease that way ios takes care of releasing the object when its no longer referred to. You do that like so -
NSMutableDictionary *dictResult = [[[NSMutableDictionary alloc] init] autorelease];
This is all you need to create dictionaries dynamically.
I think what you're asking for is how to have multiple mutable dictionaries dynamically created. You haven't said where the numbering scheme is coming from, so you may need to modify this solution for your purposes.
What you want is an array or dictionary of dictionaries.
Make one NSMutableDictionary called something like dictionaryContainer. Then, when you want to create dictionary number 7, do
NSMutableDictionary *aDictionary = [NSMutableDictionary new];
[dictionaryContainer setObject:aDictionary forKey:[NSNumber numberWithInt:7]];
To recall that dictionary, do
NSMutableDictionary *theSameDictionary = [dictionaryContainer objectForKey:[NSNumber numberWithInt:7]];
You don't have to hard code the 7, you can get it from anywhere and pass it in as an integer variable.
If I got your question correctly, this is pretty easy
#interface MyClass {
NSMutableDictionary *dict;
NSMutableArray *arr;
}
#property (nonatomic, retain) NSMutableDictionary *dict;
#property (nonatomic, retain) NSMutableArray *arr;
#end
Implementation file
#import "MyClass.h"
#implementation MyClass
#synthesize dict;
#synthesize arr;
- (id) init {
self = [super init];
if (self) {
dict = [[NSMutableDictionary alloc] init];
arr = [[NSMutableArray alloc] init];
}
return self;
}
- (void) dealloc {
[dict release];
[arr release];
[super dealloc];
}
- (void) otherStuff {
[dict setObject: #"value" forKey: #"key"];
[arr addObject: #"item"];
}
#end
usage from another class:
...
MyClass *instance = [MyClass new];
[instance.dict setObject: #"value" forKey: #"key"];
NSLog(#"Array items: %#", instance.arr);
[instance release];
...

Storing objects in an Array

I'm working with a database, and trying to store the rows of a table as dictionary in an Array.
#import "RootViewController.h"
#import "ProgettoAppDelegate.h"
#import "AddItemViewController.h"
#import "DetailViewController.h"
#include <sqlite3.h>
#implementation RootViewController
#synthesize nibLoadedCell;
#synthesize addItem;
NSNumberFormatter *priceFormatter;
NSDateFormatter *dateFormatter;
NSMutableArray *shoppingListItems; <--i created here...
NSDictionary *editItem;
-(void) loadDataFromDb {
//apriamo il database
sqlite3 *db;
int dbrc; //Codice di ritorno del database (database return code)
ProgettoAppDelegate *appDelegate = (ProgettoAppDelegate *) [UIApplication sharedApplication].delegate;
const char *dbFilePathUTF8 = [appDelegate.dbFilePath UTF8String];
dbrc = sqlite3_open(dbFilePathUTF8, &db);
if (dbrc) {
NSLog(#"Impossibile aprire il Database!");
return;
}
//database aperto! Prendiamo i valori dal database.
sqlite3_stmt *dbps; //Istruzione di preparazione del database
NSString *queryStatementNS = #"select key, item, price, groupid, dateadded from shoppinglist order by item";
const char *queryStatement = [queryStatementNS UTF8String];
dbrc = sqlite3_prepare_v2(db, queryStatement, -1, &dbps, NULL);
//Richiamo la funzione sqlite3_step() finché ho righe nel database
while ((dbrc = sqlite3_step(dbps)) == SQLITE_ROW) {
int primaryKeyValueI = sqlite3_column_int(dbps, 0);
NSNumber *primaryKeyValue = [[NSNumber alloc] initWithInt:primaryKeyValueI];
NSString *itemValue = [[NSString alloc] initWithUTF8String:(char*) sqlite3_column_text(dbps, 1)];
double priceValueD = sqlite3_column_double(dbps, 2);
NSNumber *priceValue = [[NSNumber alloc] initWithDouble:priceValueD];
int groupValueI = sqlite3_column_int(dbps, 3);
NSNumber *groupValue = [[NSNumber alloc] initWithInt:groupValueI];
NSString *dateValueS = [[NSString alloc] initWithUTF8String:(char*) sqlite3_column_text(dbps, 4)];
NSDate *dateValue = [dateFormatter dateFromString: dateValueS];
NSMutableDictionary *rowDict = [[NSMutableDictionary alloc] initWithCapacity:5];
[rowDict setObject:primaryKeyValue forKey: ID_KEY];
[rowDict setObject:itemValue forKey: ITEM_KEY];
[rowDict setObject:priceValue forKey: PRICE_KEY];
[rowDict setObject:groupValue forKey: GROUP_ID_KEY];
[rowDict setObject:dateValue forKey: DATE_ADDED_KEY];
[shoppingListItems addObject: rowDict];
NSLog(#"%d", [shoppingListItems count]); //I have a Breakpoint here!
//rilascio tutti gli elementi
[dateValue release];
[primaryKeyValue release];
[itemValue release];
[priceValue release];
[groupValue release];
[rowDict release];
}
}
using Breakpoint at the end of the procedure, i can see that in the variables there are the contents of the database, but array "shoppingListItems" is empty. (count = 0)
If you are brave enough to take a look, here there is the entire project: http://cl.ly/9uvb
You need to declare all your variables as instance variables, i mean in the .h file as shown below
// .h
#interface RootViewController : UITableViewController {
UITableViewCell *nibLoadedCell;
AddItemViewController *addItem;
IBOutlet UITableView *tableView;
NSNumberFormatter *priceFormatter;
NSDateFormatter *dateFormatter;
NSMutableArray *shoppingListItems; // <--- this is only a declaration (not creates the object)
NSDictionary *editItem;
}
And correctly initialize the objects, viewDidLoad is a good place to do this work:
//.m
- (void)viewDidLoad
{
[super viewDidLoad];
shoppingListItems = [NSMutableArray new]; // <---- This create the object
// other initialization ....
if (!dateFormatter) {
dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setTimeZone: [NSTimeZone timeZoneWithAbbreviation:#"UTC"]];
[dateFormatter setDateFormat:#"yyy-MM-dd HH:mm:ss"];
}
if (! priceFormatter) {
priceFormatter = [[NSNumberFormatter alloc] init];
[priceFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];
}
self.navigationItem.leftBarButtonItem = self.editButtonItem;
}
Your problem resides on a nil value for shoppingListItems also dont forget to release the variable on your dealloc method
You have not shown the definition of shoppingListItems but there are two common problems when adding to an array:
The array is an NSArray and not a NSMutableArray as it must be
The array is nil - you may have created it using [NSMutableArray array] without explicit retain?
Yeah, checked your code - you never initialise it at all. Fix that and you should be OK.
I don't see anything in your code above that creates the array. If shoppingListItems is nil, then those -addObject: messages do nothing.
It sounds like you aren't ever actually creating the array to go in shoppingListItems, so it's nil.

iphone listview with several cells

I have been able to make the listview show a single field of data using parts of the code like below.
NSMutableArray *array;
..
..
array = [[NSMutableArray alloc] init];
[array addObject:#"John Doe"];
However I want to keep several fields, like:
Name
ID
Date of Birth
I assume the NSMutableArrary is a NSString but I need something like a struct in C that holds the fields I need.
The ID would be "Hidden" but I need to access it when the user clicks on the line. How I access the ID and the other fields? How do I set this up so the list has the information?
Does anyone have any example code that might explain how to do this?
EDIT #1: Thanks for the comments, but I am too new to iPhone and really need to find example code on how to do this. While the comments make it sound like can do this, I dont know where to start. Can someone post example code for the idea of 3 fields?
EDIT #2: I have tried everything so far, is the the correct way to do this or should I use the ideas below?
Userrec.m
#import "UserRec.h"
#implementation Userrec
#synthesize Name, ID;
-(id)initWithName:(NSString *)n ID:(NSString *)d {
self.Name = n;
self.ID = d;
return self;
}
#end
UserRec.h
#import <UIKit/UIKit.h>
#interface Userrec : NSObject {
NSString *Name;
NSString *ID;
}
#property (nonatomic, retain) NSString *Name;
#property (nonatomic, retain) NSString *ID;
-(id)initWithName:(NSString *)n ID:(NSString *)d;
#end
UserList.m
#synthesize userrecs;
…
- (void)viewDidLoad {
[super viewDidLoad];
NSString *Name = #"Name";
NSString *ID = #"IID";
Userrec *userrec = [[Userrec alloc] initWithName:Name ID:ID ];
[userrecs addObject:userrec];
NSLog(#"Count %d",[userrecs count]);
[userrec release];
NSLog(#"Count %d",[userrecs count]);
}
After I addobject and check the count its = 0. So I assume something is wrong?
NSMutableDictionary is the best way to go. You can do something as follows:
NSMutableDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:#"John Doe", #"Name", [NSNumber numberWithInt:5], #"ID", nil];
You can keep adding as many fields as you like with that same template, even NSArray objects. I'd look up the documentation if you have any more trouble. Remember, you can only store pointers to objects in an NSDictionary. Things like
NSMutableDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:#"John Doe", #"Name", 5, #"ID", nil];
won't work. Good Luck!
Take a look at an NSMutableDictionary it seems like the exact thing you would want to use
Edit:
Here's some sample code
NSMutableArray *myData = [[NSMutableArray alloc] init];
NSMutableDictionary *myRow = [[NSMutableDictionary alloc] init];
[myRow setObject:#"John Doe" forKey:#"Name"];
[myRow setObject:#"4738" forKey:#"ID"];
[myRow setObject:#"1/23/45" forKey:#"DOB"];
[myData addObject:myRow];
[myRow release];
//Repeat from dictioanry alloc through release for each row you need to add
To display this in a UITableView, you need to have a UITableViewController class. In there override the cellForRowAtIndexPath: function. here is a simple implementation of that function
-(UITableViewCell*) tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSInteger row = [indexPath row];
static NSString *kCellID = #"cellID";
UITableViewCell *cell = nil;
cell = [tableView dequeueReuseableCellWithIdentifier:kCellID];
if ( cell == nil )
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:kCellID] autorelease];
}
NSMutableDictionary curRow = [myData objectAtIndex:row];
cell.textLabel.text = [curRow objectForKey:#"Name"];
return cell;
}

How to create Array of Array in iPhone?

I want to create a nested array or multidimensional array.
In my data is,
FirstName class year dept lastName
Bob MBA 2000 Comp Smith
Jack MS 2001 Comp McDonald
NSMutableArray *section = [[NSMutableArray alloc] init];
I want to put my data into the section Array.
Eg:
section[0] = [FirstName,LastName];
section[1] = [class, year, dept];
So how can i put the values into array like that.
Please help me out.
Thanks
I would recommend creating a custom data storage class. You could call it PDPerson.h You'll also need the .m file. For each property, do something like this:
In the .h: Declare each of your properties like so:
#interface PDPerson : NSObject{
}
#property(nonatomic, retain) NSString *firstName;
#property(nonatomic, retain) NSString *lastName;
#property(nonatomic, retain) NSString *class;//May want to consider renaming
#property(nonatomic, retain) NSString *year;
#property(nonatomic, retain) NSString *dept;
#end
Then in the .m:
#implementation
#synthesize firstName, lastName;
#synthesize class, year dept;
-(void)dealloc{
[firstName release];
[lastName release];
[class release];
[year release];
[dept release];
}
Each time you want to create a new "Person" in your array, do this:
PDPerson *person = [[PDPerson alloc]init];
You can then easily set the properties of the object like so:
person.firstName = #"John";
person.lastName = #"Smith";
person.class = #"Math";
person.year = #"1995";
person.dept = #"Sciences";
And retrieve them:
firstNameLabel.text = person.firstName;
The nice thing about these objects is that all you have to do now is add the person object to your array:
NSMutableArray *personArray = [[NSMutableArray alloc] init];
[personArray addObject:person];
NSArray *section1 = [NSArray arrayWithObjects: #"1,1", #"1,2", #"1,3", nil];
NSArray *section2 = [NSArray arrayWithObjects: #"2,1", #"2,2", #"2,3", nil];
NSArray *section3 = [NSArray arrayWithObjects: #"3,1", #"3,2", #"3,3", nil];
NSArray *sections = [NSArray arrayWithObjects: section1, section2, section3, nil];
int sectionIndex = 1;
int columnIndex = 0;
id value = [[sections objectAtIndex:sectionIndex] objectAtIndex:columnIndex];
NSLog(#"%#", value); //prints "2,1"
Be warned, this isn't a flexible way of storing data. Consider using CoreData or creating your own classes to represent the data.
You can just nest multiple NSArray instances within an NSArray.
For example:
NSMutableArray* sections = [[NSMutableArray alloc] init];
for (int i = 0; i < numberOfSections; i++)
{
NSMutableArray* personsInSection = [[NSMutableArray alloc] init];
[sections insertObject:personsInSection atIndex:i];
for (int x = 0; x < numberOfPersons; x++)
{
Person* person = [[Person alloc] init];
[personsInSection insertObject:person atIndex:x];
}
}
This may seem like overkill when coming from languages such as C++ or Java, where multidimensional arrays can be created simply by using multiple sequare brackets. But this is way things are done with Objective-C and Cocoa.