insert array into tableview - iphone

I'm having trouble inserting an array to the table view. I have an array and i stored it in alDescArray.
Which is alDescArray = (
"Block1",
"Block2",
"Block3"
) where its printed in through NSLog. The table doesn't show anything which part of my code when wrong?
- (void)viewDidLoad
{
NSArray *BusRoute = alightDesc;
int i;
int count = [BusRoute count];
for (i = 0; i < count; i++)
{
NSDictionary *dic = [BusRoute objectAtIndex: i];
NSDictionary *STEPS = [dic valueForKey:#"STEPS"];
alDescArray = [STEPS valueForKey:#"AlightDesc"];
}
[super viewDidLoad];
}
and this is the code for tableview
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [alDescArray count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
cell.textLabel.text = [alDescArray objectAtIndex:indexPath.row];
return cell;
}
Pls help thanks

Apparently your tableview's delegate / dataSource is not set.
.h
YourClassName : ParentClass <UITableViewDelegate, UITableViewDataSource>
.m
- (void)viewDidLoad
{
yourTableView.delegate = self;
yourTableView.dataSource = self;
NSArray *BusRoute = alightDesc;
int i;
int count = [BusRoute count];
for (i = 0; i < count; i++)
{
NSDictionary *dic = [BusRoute objectAtIndex: i];
NSDictionary *STEPS = [dic valueForKey:#"STEPS"];
alDescArray = [STEPS valueForKey:#"AlightDesc"];
}
[super viewDidLoad];
}

Related

can we remove values from NSMutableArray on a button click

I have an NSMutableArray in which I insert the values when any user selects the field and this is an multi selection field so I can insert the data according to multiple selection in NSMutableArray but when user unselects an selected field then how can I remove the value of unselected field which are selected earlier.
yourviewcontroller.h
NSMutableArray *arr_select;
NsMutableArray *your_arry;
Yourviewcontroller.m
- (void)viewDidLoad
{
arr_select=[[NSMutableArray alloc]init];
for (int i = 0; i < [your_arry count]; i++)
{
[arr_select addObject:#"0"];
[arr_select retain];
}
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSLog(#"%#",arr_select);
NSNumber *anumber = [NSNumber numberWithInteger:indexPath.row];
if([[arr_select objectAtIndex:indexPath.row] isEqualToString:#"0"])
{
[arr_select replaceObjectAtIndex:indexPath.row withObject:#"1"];
[arr_select retain];
}
else
{
[arr_select replaceObjectAtIndex:indexPath.row withObject:#"0"];
[arr_select retain];
}
NSLog(#"%#",arr_select);
[tableView reloadData];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
if([[arr_select objectAtIndex:indexPath.row]isEqualToString:#"0"])
{
cell.accessoryType = UITableViewCellAccessoryNone;
}
else
{
cell.accessoryType = UITableViewCellAccessoryCheckmark;
}
}
-(IBAction)Done:(id)sender
{
NSLog(#"%#",arr_select);
NSLog(#"%#",co_arr);
arr_data = [[NSMutableArray alloc] init];
for (int i = 0; i <[arr_select count]; i++)
{
if([[arr_select objectAtIndex:i] isEqualToString:#"1"])
{
NSLog(#"%d",i);
[arr_data addObject:[co_arr objectAtIndex:i]];
[arr_data retain];
}
}

Accordion style tableview without using sections

I am interning for the summer on an iOS native app development team. They gave me a task of accomplishing removing/inserting cells in a tableview without using sections. I am struggling with the task if anyone could take a look at the code and try to help me out id be much appreciated. I am getting some removals and disappearances but it is not staying consistent, and it is adding cells that are already visible. (consistency in the sense that once i insert rows, row 3 is now row 5, and my modulo arithmetic gets thrown off.
I am very new to objective c so any advice / help would be much appreciated.
#implementation MasterViewController
NSMutableArray * levels;
NSMutableArray * array;
NSMutableIndexSet * expandedSections;
NSMutableDictionary * dict;
-(BOOL) loadFiles{
// NSFileManager * fileManager = [NSFileManager defaultManager];
if (!expandedSections) {
expandedSections = [[NSMutableIndexSet alloc]init];
}
array = [[NSMutableArray alloc]init];
levels = [[NSMutableArray alloc]init];
for (int i=0; i<20; i++) {
NSString * temp = [[NSString alloc]initWithFormat:#"This is row : %i ", i];
[array addObject:temp];
}
for (int i=0; i<20; i++) {
NSNumber * temp = [[NSNumber alloc]initWithInt:i];
[levels addObject:temp];
}
dict = [[NSMutableDictionary alloc]initWithObjects:array forKeys:levels];
NSLog(#"TEST: %#", [dict objectForKey:[levels objectAtIndex:1]]);
return YES;
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
self.title = NSLocalizedString(#"Master", #"Master");
}
return self;
}
- (void)viewDidLoad {
[super viewDidLoad];
[self loadFiles];
// Do any additional setup after loading the view, typically from a nib.
self.navigationItem.leftBarButtonItem = self.editButtonItem;
UIBarButtonItem *addButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:#selector(insertNewObject:)];
self.navigationItem.rightBarButtonItem = addButton;
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)insertNewObject:(id)sender {
if (!_objects) {
_objects = [[NSMutableArray alloc] init];
}
[_objects insertObject:[NSDate date] atIndex:0];
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
[self.tableView insertRowsAtIndexPaths:#[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
}
#pragma mark - Table View
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
if ([expandedSections containsIndex:section]) {
return [array count] +2;
}
return [array count];
}
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath: (NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}
if (!(indexPath.row %3)==0) {
cell.textLabel.text = [dict objectForKey:[levels objectAtIndex:indexPath.row]];
[cell setIndentationLevel:2];
cell.accessoryType = UITableViewCellAccessoryNone;
cell.accessoryView = nil;
} else {
cell.textLabel.text = [dict objectForKey:[levels objectAtIndex:indexPath.row]];
[cell setIndentationLevel:0];
}
return cell;
}
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
// Return NO if you do not want the specified item to be editable.
return YES;
}
- (void)tableView:(UITableView *)tableView commitEditingStyle: (UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
if (editingStyle == UITableViewCellEditingStyleDelete) {
[_objects removeObjectAtIndex:indexPath.row];
[tableView deleteRowsAtIndexPaths:#[indexPath] withRowAnimation:UITableViewRowAnimationFade];
} else if (editingStyle == UITableViewCellEditingStyleInsert) {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
}
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
if (!self.detailViewController) {
self.detailViewController = [[DetailViewController alloc] initWithNibName:#"DetailViewController" bundle:nil];
}
BOOL currentlyExpanded = [expandedSections containsIndex:indexPath.row];
//[tableView deselectRowAtIndexPath:indexPath animated:YES];
NSLog(#"CurrentlyExpanded : %d", currentlyExpanded);
NSLog(#"TEST: %#", [dict objectForKey:[levels objectAtIndex:indexPath.row ]]);
if ((indexPath.row %3)==0) {
// only first row toggles exapand/collapse
[tableView deselectRowAtIndexPath:indexPath animated:YES];
NSInteger section = indexPath.section;
BOOL currentlyExpanded = [expandedSections containsIndex:section];
NSInteger rows;
NSMutableArray *tmpArray = [NSMutableArray array];
if (currentlyExpanded) {
rows = 2;
[expandedSections removeIndex:section];
} else {
[expandedSections addIndex:section];
rows = 2;
}
for (int i=indexPath.row+1; i<=(indexPath.row + rows); i++) {
NSIndexPath *tmpIndexPath = [NSIndexPath indexPathForRow:i
inSection:section];
[tmpArray addObject:tmpIndexPath];
}
if (currentlyExpanded) {
[tableView deleteRowsAtIndexPaths:tmpArray
withRowAnimation:UITableViewRowAnimationTop];
} else {
[tableView insertRowsAtIndexPaths:tmpArray
withRowAnimation:UITableViewRowAnimationTop];
}
}
if ((indexPath.row %3)>0) {
NSDate *object = _objects[indexPath.row];
self.detailViewController.detailItem = object;
[self.navigationController pushViewController:self.detailViewController animated:YES];
}
}
#end
Take a look at TLIndexPathTools. It greatly simplifies building dynamic tables like this. It does all the work calculating and performing the batch updates for you. Try running the Outline sample project. It demonstrates how to build an expandable tree without using sections. You can accomplish what you need by just building up a two-level tree.

Want to display the array values in the table

Table View:
-(NSInteger) numberOfSectionsInTableView:(UITableView *)tableView{
return 1;
}
-(NSInteger) tableView:(UITableView *)table numberOfRowsInSection:(NSInteger)section{
return [self.detailArray count];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
tableView.delegate = self;
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10.0f, 5.0f, 300.0f, 30.0f)];
label.text=[NSString stringWithFormat:#"%#",[self.detailArray objectAtIndex:indexPath.row]];
label.numberOfLines = 3;
label.font = [UIFont fontWithName:#"Helvetica" size:(12.0)];
label.lineBreakMode = UILineBreakModeWordWrap;
label.textAlignment = UITextAlignmentLeft;
[cell.contentView addSubview:label];
[label release];
[self.myTableView reloadData];
return cell;
}
I want to store the detail (array value) in the tableView.I used both method numberOfRowsInSection and cellForRowAtIndexPath but the table display null. How can I display?
Make property for NSMutable array in .h
#property (nonatomic,retain) NSMutableArray *detailArray;
and synthesize it in .m
#synthesize detailArray=_detailArray;
and change this line
NSMutableArray *detail=[[stepsArr objectAtIndex:i] objectForKey:#"html_instructions"] ;
to
_detailArray=[[stepsArr objectAtIndex:i] objectForKey:#"html_instructions"] ;
then use _detailArray for displaying table data.
- (NSInteger)tableView:(UITableView *)tableView
numberOfRowsInSection:(NSInteger)section {
return [_detailArray count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath {
// _detailArray objects for date population.
}
Your Code :
NSString *url = [NSString stringWithFormat:#"http://maps.googleapis.com/maps/api/directions/json?origin=%#&destination=%f,%f&sensor=false",startPoint,midannotation.coordinate.latitude,midannotation.coordinate.longitude];
NSURL *googleRequestURL=[NSURL URLWithString:url];
dispatch_async(kBgQueue, ^{
NSData* data = [NSData dataWithContentsOfURL: googleRequestURL];
NSString *someString = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
// NSLog(#"data:%#",someString);
NSError* error;
NSMutableDictionary* parsedJson = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSArray *allkeys = [parsedJson allKeys];
for(int i = 0; i < allkeys.count; i++){
if([[allkeys objectAtIndex:i] isEqualToString:#"routes"]){
arr = [parsedJson objectForKey:#"routes"];
dic = [arr objectAtIndex:0];
// NSLog(#"ALL KEYS FROM ROUTE: %#", [dic allKeys]);
legs = [dic objectForKey:#"legs"];
// NSLog(#"legs array count %d", legs.count);
for(int i = 0; i < legs.count; i++){
stepsArr = [[legs objectAtIndex:i] objectForKey:#"steps"];
for (int i = 0; i < stepsArr.count; i++) {
NSLog(#"HTML INSTRUCTION %#", [[stepsArr objectAtIndex:i] objectForKey:#"html_instructions"]);
NSLog(#"############################");
NSMutableArray *detail=[[stepsArr objectAtIndex:i] objectForKey:#"html_instructions"] ;
}
}
}
}
});
first you go to your .h file -->
#property (nonatomic, strong) NSMutableArray * detailsArray;
In .m file -->
#synthesize detailsArray;
replace this code
NSMutableArray *detail=[[stepsArr objectAtIndex:i] objectForKey:#"html_instructions"] ;
by this -->
self.detailsArray = [[stepsArr objectAtIndex:i] objectForKey:#"html_instructions"];
# using table datasource methods
- (NSInteger)tableView:(UITableView *)tableView
numberOfRowsInSection:(NSInteger)section {
return [self.detailsArray count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
cell.titleLabel.text = [self.detailsArray objectAtIndex: indexPath.row ];
return cell;
}
}
//Note Please set the delegate method of table , if you write the code programmatically means tableView.delgate = self;
Use this :
self.detaisArray = [[NSMutableArray alloc] init];
// Do any additional setup after loading the view, typically from a nib.
NSString *url = [NSString stringWithFormat:#"http://maps.googleapis.com/maps/api/directions/json?origin=%#&destination=%f,%f&sensor=false",startPoint,midannotation.coordinate.latitude,midannotation.coordinate.longitude];
NSURL *googleRequestURL=[NSURL URLWithString:url];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSData* data = [NSData dataWithContentsOfURL: googleRequestURL];
NSString *someString = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
// NSLog(#"data:%#",someString);
NSError* error;
NSMutableDictionary* parsedJson = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSArray *allkeys = [parsedJson allKeys];
for(int i = 0; i < allkeys.count; i++){
if([[allkeys objectAtIndex:i] isEqualToString:#"routes"]){
NSArray *arr = [parsedJson objectForKey:#"routes"];
NSDictionary *dic = [arr objectAtIndex:0];
// NSLog(#"ALL KEYS FROM ROUTE: %#", [dic allKeys]);
NSArray *legs = [dic objectForKey:#"legs"];
// NSLog(#"legs array count %d", legs.count);
for(int i = 0; i < legs.count; i++){
NSArray *stepsArr = [[legs objectAtIndex:i] objectForKey:#"steps"];
for (int i = 0; i < stepsArr.count; i++) {
NSLog(#"HTML INSTRUCTION %#", [[stepsArr objectAtIndex:i] objectForKey:#"html_instructions"]);
NSLog(#"############################");
[self.detaisArray addObject:[[stepsArr objectAtIndex:i] objectForKey:#"html_instructions"] ];
if(i == legs.count-1){
self.myTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 20, 320, 400) style:UITableViewStylePlain];
self.myTableView.delegate = self;
self.myTableView.dataSource = self;
[self.view addSubview:self.myTableView];
}
}
}
}
}
});
first checked you connect your tableview delegate set self...
second checked youn row count pr detailarray cont in numberOfRowsInSection its may b zero
1st Declare Your Array in .h
like this
#property(strong,nonatomic)NSMutableArray * name;
And intialize into .m Init() method
name=[NSMutableArray alloc]initWithObjects:#"a",#"b", nil];
// TableView Delegate Method To Display Array Data into Tableview.
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return name.count; //Give Your Array Name Here.
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
cell.textLabel.text=[NSString stringWithFormat:#"%#",[name objectAtIndex:indexPath.row]];
return cell;
}
Try this code.

iphone - come to the annotation when cell is clicked

In my mapview project, I have passed an NSMutableArray of my custom annotation to a table view.
in tha mapview .m code:
MyLocation *nota =[[MyLocation alloc] initWithName:name time:horario];
[_mapView addAnnotation:nota]; //add location to map
[mapViewAnnotations addObject:nota]; //copy "nota" to the new array...
}
TablaViewController *tablaController =[[TablaViewController alloc]initWithNibName:#"TablaViewController" bundle:nil];
tablaController.locationFromMap = mapViewAnnotations; //... then I pass array to table
in the table View:
- (void)viewDidLoad
{
[super viewDidLoad];
self.navigationItem.title = #"Locations";
listOfItems = [[NSMutableArray alloc] init];
for (int i = 0; i < [locationFromMap count]; i++){
MyLocation *location = [locationFromMap objectAtIndex:i];
//Add items
[listOfItems addObject:location.name];
NSLog(#" list count : %d",[listOfItems count]);
}
}
where locationFromMap is a NSmtable array of custom location with some atributes like name, subname etc.
Using :
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
NSString *cellValue = [listOfItems objectAtIndex:indexPath.row];
cell.textLabel.text = cellValue;
return cell;
}
location "name" are correctly showed in the table.
My question is how can a come back to map focusing on a concrete location when the relative row is clicked. Perarps my method is wrong ?
Thanks in advance.
so:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
MyLocation *loc = [locationFromMap objectAtIndex:indexPath.row];
MKCoordinateRegion r = MKCoordinateRegionMake(loc.coordinate, MKCoordinateSpanMake(0.005, 0.005));
[self.mapView setRegion:r animated:YES];
}
(typed inline but something like this)

UITableView: use object from dictionary as title on detail view

I have the following code to make a table from string turned into a dictionary:
- (void)viewDidLoad {
[super viewDidLoad];
testArray = [[NSArray alloc] init];
NSString *testString = #"Sam|26,Hannah|22,Adam|30,Carlie|32";
testArray = [testString componentsSeparatedByString:#","];
dict = [NSMutableDictionary dictionary];
for (NSString *s in testArray) {
testArray2 = [s componentsSeparatedByString:#"|"];
[dict setObject:[testArray2 objectAtIndex:1] forKey:[testArray2 objectAtIndex:0]];
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
}
// Configure the cell.
if (testArray.count >indexPath.row) {
cell.textLabel.text = [[dict allKeys] objectAtIndex:[indexPath row]];
cell.detailTextLabel.text = [dict objectForKey:cell.textLabel.text];
}
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
return cell;
}
What I would like is for the selected row title to be set as the title on my detail view.
I tried with:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
self.detailController.title = [[dict allKeys] objectAtIndex:[indexPath row]];
[self.navigationController pushViewController:self.detailController animated:YES];
}
But I get an "EXC_BAD_ACCESS" error.
It works fine if I use #"1" as title, it's just something with my dictionary call that's wrong, I assume.
Make dict a retained dictionary instead of an autoreleased one.
I.E. declare it maybe like this:
dict = [[NSMutableDictionary alloc] initWithCapacity: [testArray count]];
in your viewDidLoad method. Make sure to release it when viewDidUnload is called.
Also, make sure of the number of keys in your dict before calling:
self.detailController.title = [[dict allKeys] objectAtIndex:[indexPath row]];
So, I would do:
if(dict && ([[dict allKeys] count] > [indexPath row])
{
self.detailController.title =
[[dict allKeys] objectAtIndex:[indexPath row]];
} else {
self.detailController.title = #"Here's a problem";
}
Did you implement these UITableView delegate methods ? All these are needed. Also can you post more detailed StackTrace.
- (NSInteger)tableView:(UITableView *)tableView
numberOfRowsInSection:(NSInteger)section
{
return [resultSet count];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (CGFloat)tableView:(UITableView *)tableView
heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 280.0;
}