get object from [myarray objectAtIndex:indexPath.row] instead of NSString - iphone

i have a custom class called contact. This class has attributes like name, address etc.
I wish to create an array of type contact and display the value of each attibute in a custom cell in UItableview.
Code to store the data in array:
while(sqlite3_step(compiledStatement) == SQLITE_ROW) {
// Read the data from the result row
NSString *aName = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 1)];
myContact.nm = aName;
NSString *aAddress = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 2)];
myContact.address = aAddress;
NSLog(#"%#",aName);
[list.details addObject:myContact];
NSLog(#"%#", list.details);
}
here details is an array declared as #property(nonatomic,retain)NSMutableArray *details; in .h
My question is that how do i retrieve the values on each index like :
[0]->name
[0]->address
[1]->name
[1]->address ....
my code in tableview.m:
cell.name.text = [details objectAtIndex:indexPath.row]; // not working
how do i solve this?

First make an object of class.
Contact *con = [details objectAtIndex:indexPath.row];
It will store all array in 'con' object.
Then, Use it by,
NSLog("Name :: %#", con.nm);
NSLog("Addr :: %#", con.address);
It'll refer Name & Address of that particular contact object.
Thanks.

[[details objectAtIndex:indexPath.row] nm];
In nm you just need to input your object. This works for me.

[details objectAtIndex:indexPath.row]; returns the Contact object. What you need is, nm property of Contact object which represents the name in your code.
Try this,
Contact *myContacts = [details objectAtIndex:indexPath.row];
cell.name.text = [myContacts nm]; //or [[details objectAtIndex:indexPath.row] nm];
Similarly you can get [myContacts address] as well.
Edit:
Based on your question in comments, the answer is:
while(sqlite3_step(compiledStatement) == SQLITE_ROW) {
Contact *myContact = [[Contact alloc] init]; //you should add this here, not outside the loop
// Read the data from the result row
NSString *aName = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 1)];
myContact.nm = aName;
NSString *aAddress = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 2)];
myContact.address = aAddress;
NSLog(#"%#",aName);
[list.details addObject:myContact];
NSLog(#"%#", list.details);
}

Well, are you looking for
cell.name.text = [[details objectAtIndex:indexPath.row] name];
?

You need:
cell.name.text = [[details objectAtIndex:indexPath.row] nm];
When you use this line:
[details objectAtIndex:indexPath.row];
It returns a object of type contact. Then you need to get the nm property which stores the name.
So you need to use like:
[[details objectAtIndex:indexPath.row] nm];

Related

Strings loaded from sqlite database leading to out of scope objects

I have a database manager which successfully loads a string from my sqlite database, and then uses it to create an object. I add multiple of these objects to an array and return it to which ever class I'm calling it from.
I have no problem using the returned array in the method I call it from, but when other methods in the class try to access it, the string element is out of scope.
Here is my relavent code.
In DBManager.m:
-(NSArray *)loadObjectData {
NSMutableArray *myArray = [[NSMutableArray alloc] init];
//prepare query and statement
NSString *query = [NSString stringWithFormat:#"SELECT * FROM object;"];
sqlite3_stmt *statement;
//perform query
if (sqlite3_prepare_v2(database, [query UTF8String], -1, &statement, nil) != SQLITE_OK)
NSLog(#"Prepare Error. '%s'", sqlite3_errmsg(database));
//get data
while (sqlite3_step(statement) == SQLITE_ROW) {
//read values
int anInt = sqlite3_column_int(statement, 0);
NSString *aString = [NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 1)];
//add new object to list
[myArray addObject:[[Object alloc] initWithID:anInt Name:aString]];
}
if(sqlite3_finalize(statement) != SQLITE_OK)
NSLog(#"Finalize statement error.");
return [myArray autorelease];
}
In XViewController.h:
NSArray *listData;
SessionData *sessionData;
#property (nonatomic, retain) NSArray *listData;
#property (nonatomic, retain) SessionData *sessionData;
In XViewController.m:
- (void)viewDidLoad
{
dbMan = [DBManager sharedDBMananager]; //its a singleton
//Load objects to display in table
self.listData = [dbMan loadObjectData];
//if i try to use listData here, it works fine.
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
//normal stuff cut out
// Configure the cell...
//the following line fails because the string in the object out of scope
cell.textLabel.text = [[listData objectAtIndex:[indexPath row]] aString];
//trying to access [[listData objectAtIndex:[indexPath row]] anInt] works fine though.
return cell;
}
If I replace the line (in my loadObjectData method):
NSString *aString = [NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 2)];
with this:
NSString *aString = #"String";
everything works fine.
Take a look at this question's accepted answer - What does assigning a literal string to an NSString with "=" actually do?
The string literal ( #"String" ) works because it is statically allocated and does not need to be retained/released. [NSString stringWithUTF8String:] creates an autoreleased string. If you are not retaining it in your initWithID:Name: method then it is being released which is why your code isn't working. In your initWithID:Name: method at a retain when you reassign the name to your object's instance variable.
In Object class have you retained this string if not then i think you should and release this string in dealloc

Get data from database.

Ok, I am able to connect to the mysql database from my iPhone app, I have set it up in a tableview. So when I call the didSelectRow method it stores the users Id number, not the indexRow number. My question is how can I use that stored id to retrieve the rest of the information, so when the row is pressed it brings up the rest of that users particular Information. I know I am not showing any code here that is because I'm writing this from my iPad, so I hope you cam follow what im trying to do and help. Thanks.
I can help u in one way that u have to store the array coming from the data base in an array in appdel u can call that array at any time where we want sample code is here
this is the array in appdb
NSMutableArray *fruit_details;
call one method in Appdb
[self readStudentFromDatabase];
then write the code here in that method
NSArray *documentpaths= NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentDir = [documentpaths objectAtIndex:0];
databasePath = [documentDir stringByAppendingPathComponent:databaseName];
fruit_details=[[NSMutableArray alloc]init];
//open the database from the users filesystem
if(sqlite3_open([databasePath UTF8String], &database)==SQLITE_OK)
{
// Setup the SQL Statement and compile it for faster access
const char *sqlStatement ="select * from stu";
sqlite3_stmt *compiledStatement;
if(sqlite3_prepare_v2(database, sqlStatement,-1, &compiledStatement , NULL)== SQLITE_OK)
{
// Loop through the results and add them to the feeds array
while (sqlite3_step(compiledStatement)==SQLITE_ROW)
{
NSString *aName =[NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement,0)];
NSString *amarks=[NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement,1)];
NSString *arank =[NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement,2)];
NSString *aaddr =[NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement,3)];
NSString *aemail =[NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement,4)];
NSString *aphno =[NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement,5)];
NSString *aage =[NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement,6)];
NSString *asex =[NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement,7)];
NSString *adate =[NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement,8)];
NSString *aimage=[NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 9)];
// // Create a new animal object with the data from the database
//animal *animal_object=[[animal alloc]initWithName:aName description:arollNO url:amarks];
//add the animal object to the animal ar
//[animals addObject:animal_object];
temp=[[NSMutableArray alloc]init];
[temp addObject:aName];
[temp addObject:amarks];
[temp addObject:arank];
[temp addObject:aaddr];
[temp addObject:aemail];
[temp addObject:aphno];
[temp addObject:aage];
[temp addObject:asex];
[temp addObject:adate];
[temp addObject:aimage];
[fruit_details addObject:temp];
}
}
sqlite3_finalize(compiledStatement);
}
sqlite3_close(database);
I think this may help u.....
Is stored id what you get from the db? My understanding is that when user select a row, you want to go to a new view and fetch the corresponding information from the db using that stored id.

how can I insert values of sqlite3 database table into NSMutableArray?

I have retrieved data from sqlite3 database table as below
NSString *name = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 0)];
NSString *price = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 1)];
now I have an NSMutableArray named as Data, I have declared and synthesized it properly, now how can I add values into it, I tried addObject, and print in NSLog, but showing null value, while there are values in name and price?
help me out
If the array is nil, it will never accept values because it doesn't exist. Even if you synthesize a property, it doesn't mean the property gets a default object assigned to it. Somebody still has to make sure an instance of NSMutableArray exists.
NSNumber *WId;
int temp1 = (int)sqlite3_column_int(walkstatement, 0);
WId = [[NSNumber alloc] initWithInt:temp1];
char *WNameCharacter;
WNameCharacter = (char *) sqlite3_column_text(walkstatement, 1);
NSString *WNameString = [[NSString alloc] initWithUTF8String:WNameCharacter];
NSMutableDictionary *tempWalk = [[NSMutableDictionary alloc] init];
[tempWalk setObject:WId forKey:#"WalkId"];
[tempWalk setObject:WNameString forKey:#"WalkName"];
[regionWalkArray addObject:tempWalk];
This worked for me please change the variables according to your requirement..

How to create image and labels using location data stored in NSArray

i have to create an 2images and 3 labels by using code (cgrectmake)and i am having X location, y location, width and height all are stored in arrays(which i have retrieved from the web services)how can i create the image and labels can any one help me
You can join the elements of an array together with the NSString componentsJoinedByString class method:
NSString myString = [myNSArray componentsJoinedByString:#"x"];
where x is the characters you'd like to appear between each array element.
Edited to add
So in your newly-added code if these are the label values:
lbl = #"zero"
lbl1 = #"one"
lbl2 = #"two"
and you want to join them together with a space character then if you did this:
NSString *temp = [labelArray componentsJoinedByString:#" "];
NSLog(#"temp = %#", temp);
then this is what would be logged:
zero one two
Edited to further add
If you are instead trying to join the label values together to make xml elements then you might do something like this:
NSString *joinedElements = [labelArray componentsJoinedByString:#"</label><label>"];
NSString *temp = [NSString stringWithFormat:#"<label>%#</label>", joinedElements];
NSLog(#"temp = %#", temp);
then this is what would be logged:
<label>zero</label><label>one</label><label>two</label>
may be this is usefull to you.
NSString *str;
str = [arrayName objectAtIndex:i(Index NO)];
OK by this easily you can access object from the array. any type of object u can fetch this way only reception object type are change in left side.
Best of Luck.
Most objects have a -description method which returns a string representation of the object:
- (NSString *)description;
For example:
NSArray *array = [NSArray arrayWithObjects:#"The", #"quick", #"brown", #"fox", nil];
NSLog(#"%#", array); // prints the contents of the array out to the console.
NSString *arrayDescription = [array description]; // a string
It would help to know what you want to do with the string (how will you use the string). Also, what kind of objects do you have in the array?
In that case, Matthew's answer is one possibility. Another might be to use an NSMutableString and append the individual items, if you need control over how the string is created:
NSMutableString *string = [NSMutableString string];
if ([array count] >= 3) {
[string appendString:[array objectAtIndex:0]];
[string appendFormat:#"blah some filler text %#", [array objectAtIndex:1]];
[string appendString:[array objectAtIndex:2]];
}

obj-c problem setting array with componentsSeperatedByString

I have a data source with about 2000 lines that look like the following:
6712,Anaktuvuk Pass Airport,Anaktuvuk Pass,United States,AKP,PAKP,68.1336,-151.743,2103,-9,A
What I am interested in is the 6th section of this string so I want to turn it into an array, then i want to check the 6th section [5] for an occurrance of that string "PAKP"
Code:
NSBundle *bundle = [NSBundle mainBundle];
NSString *airportsPath = [bundle pathForResource:#"airports" ofType:#"dat"];
NSData *data = [NSData dataWithContentsOfFile:airportsPath];
NSString *dataString = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease];
NSArray *dataArray = [dataString componentsSeparatedByString:#"\n"];
NSRange locationOfAirport;
NSString *workingString = [[NSString alloc]initWithFormat:#""];
NSString *searchedAirport = [[NSString alloc]initWithFormat:#""];
NSString *airportData = [[NSString alloc]initWithFormat:#""];
int d;
for (d=0; d < [dataArray count]; d=d+1) {
workingString = [dataArray objectAtIndex:d];
testTextBox = workingString; //works correctly
NSArray *workingArray = [workingString componentsSeparatedByString:#","];
testTextBox2 = [workingArray objectAtIndex: 0]; //correctly displays the first section "6712"
testTextBox3 = [workingArray objectAtIndex:1] //throws exception index beyond bounds
locationOfAirport = [[workingArray objectAtIndex:5] rangeOfString:#"PAKP"];
}
the problem is that when the workingArray populates, it only populates with a single object (the first component of the string which is "6712". If i have it display the workingString, it correctly displays the entire string, but for some reason, it isn't correctly making the array using the commas.
i tried it without using the data file and it worked fine, so the problem comes from how I am importing the data.
ideas?
You code works. You should run it with the debugger to see what's happening. At a guess, your input data isn't what you think it is - possibly a different encoding, or different line endings.
See sample:
NSString *dataString = #"6712,Anaktuvuk Pass Airport,Anaktuvuk Pass,United States,AKP,PAKP,68.1336,-151.743,2103,-9,A";
NSArray *dataArray = [dataString componentsSeparatedByString:#"\n"];
for (NSString *workingString in dataArray) {
NSString *testTextBox = workingString; //works correctly
NSArray *workingArray = [workingString componentsSeparatedByString:#","];
NSString *testTextBox2 = [workingArray objectAtIndex: 0]; //correctly displays the first section "6712"
NSString *testTextBox3 = [workingArray objectAtIndex:1]; //throws exception index beyond bounds
NSRange locationOfAirport = [[workingArray objectAtIndex:5] rangeOfString:#"PAKP"];
}
there was a problem in the data where there were a few "\"s that caused the errors.