How to delete UITableViewCell from within same cell? - ios

I have a UITableView with custom table view cell.
That cell has a custom delete button. Button action is within the cell class.
I can't reload the table from cell class after deleted row from db. If I try to get table view from cell.superview or cell.superview.superview, the app crashes.
This is cell implementation
#implementation pixSavedTableViewCell
- (IBAction)deleteBusiness:(id)sender {
NSLog(#"DELETING BUSINESS cell");
self.hidden=YES;
pixDBManager *dbConnection = [[pixDBManager alloc]init];
dbConnection.businessName = self.nameLable.text;
[dbConnection deleteBusiness];
//[(UITableView *)self.superview.superview reloadData];
}
#end
This will delete data from
-(void)deleteBusiness
{
NSLog(#"DELETING BUSINESS");
char *error;
if(sqlite3_open([dbPathString UTF8String], &businessDB)==SQLITE_OK){
NSString *deleteStatement = [NSString stringWithFormat:#"DELETE FROM SAVEDBUSINESS WHERE 'NAME'='%#'",_businessName];
const char *delete_stmt = [deleteStatement UTF8String];
NSLog(#"%s",delete_stmt);
if (sqlite3_exec(businessDB, delete_stmt, NULL, NULL, &error)==SQLITE_OK) {
NSLog(#"Business Deleted");
}
else{
NSLog(#"Cant Delete Data");
}
sqlite3_close(businessDB);
}
else{
NSLog(#"Cant Open Data Base");
}
}
This is my view controller implementation
#implementation pixSavedViewController
{
NSMutableArray *businessArray;
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
pixDBManager *dbConnection = [[pixDBManager alloc]init];
businessArray = [[NSMutableArray alloc]init];
[dbConnection createOrOpenDB];
businessArray = [dbConnection getSavedBusiness];
// Do any additional setup after loading the view.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return businessArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *customcellidentifier = #"CustomCell3";
pixSavedTableViewCell *cell = (pixSavedTableViewCell *)[tableView dequeueReusableCellWithIdentifier:customcellidentifier];
if (cell == nil) {
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"Savedcell" owner:self options:nil];
cell = [nib objectAtIndex:0];
}
pixBusinessDetails *details = [[pixBusinessDetails alloc]init];
details = [businessArray objectAtIndex:indexPath.row];
cell.nameLable.text = details.name;
cell.addressLable.text = details.address;
cell.descriptionLable.text = details.description;
cell.scoreLable.text = details.score;
cell.votesLable.text = details.votes;
NSLog(#"Business Detail %#\n %#\n %#\n %#\n %#\n %#\n",details.name, details.address,details.description,details.score,details.votes,details.imageId);
return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 130;
}

Rather than deleting the data from within the UITableViewCell, you should instead call a method in your UIViewController which will delete the data and then reload the table.
On way to do this is to create a protocol for your UIViewController to conform to:
#protocol pixSavedTableViewCellDelegate
- (void)deleteBuisness:(NSString *) businessName
#end
#interface pixSavedTableViewCell : UITableViewCell
#property (nonatomic, weak) id<pixSavedTableViewCellDelegate> delegate;
#end
Then in you UITableViewCell you change your delete method to:
- (IBAction)deleteBusiness:(id)sender {
[self.delegate deleteBuisness:self.nameLabel.text];
}
In your UIViewController you then implement the protocol:
#interface pixSavedViewController <pixSavedTableViewCellDelegate>
#end
#implementation pixSavedViewController
#pragma mark - pixSavedTableViewCellDelegate
- (void)deleteBuisness:(NSString *) businessName
{
pixDBManager *dbConnection = [[pixDBManager alloc]init];
dbConnection.businessName = businessName;
[dbConnection deleteBusiness];
[self.tableView reloadData];
}
You'll also need to set the delegate when creating the cell:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
//All your current code
cell.delegate = self;
return cell;
}

This is what the delegate pattern is for, in my opinion:
Make your UITableViewController a delegate of your custom cell.
MyCustomCell *cell = ....
cell.deleteDelegate = self
//in your UITableViewController
- (void)willDeleteCustomCell:(MyCustomCell*)cell
{
}
//on your cell
- (IBAction)deleteBusiness:(id)sender
{
[self.deleteDelegate willDeleteCustomCell:self];
//rest of your delete code
}

Related

How i pass Data from SlideOut TableViewController to TableView embedded in ViewController

updated my .h and .m files. As mentioned i have to get the data (plist
file) from the ViewController1 tableview once rows (multiple) have
been selected to the tableview in the second view controller. Here i struggle mostly since days :)
#import "ViewController1.h"
#interface UIViewController () <UITableViewDataSource, UITableViewDelegate> #end
#implementation ViewController1 {
NSArray *tableData; }
- (void)viewDidLoad {
[super viewDidLoad];
NSString *path = [[NSBundle mainBundle] pathForResource:#"TableData" ofType:#"plist"];
NSDictionary *dictionary = [[NSDictionary alloc] initWithContentsOfFile:path];
tableData = [dictionary objectForKey:#"Cupcakes"];}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated. }
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [tableData count]; }
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *simpleTableIdentifier = #"SimpleTableItem";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
}
cell.textLabel.text = [tableData objectAtIndex:indexPath.row];
cell.detailTextLabel.text = [tableData objectAtIndex:indexPath.row];
return cell;
}
#end
import "ViewController.h"
#import "SWRevealViewController.h"
#interface ViewController ()
#end
#implementation ViewController
#synthesize count;
#synthesize countLabel;
#synthesize negative;
- (void)viewDidLoad
{
negative = TRUE;
[super viewDidLoad];
_barButton.target = self.revealViewController;
_barButton.action = #selector(revealToggle:);
[self.view addGestureRecognizer:self.revealViewController.panGestureRecognizer];
}
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
}
#pragma mark - TableView Deletage and Datasouce methods
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return 10;
}
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
return YES;
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
if (editingStyle == UITableViewCellEditingStyleDelete) {
}
}
- (IBAction)plus:(UIButton*)sender{
count++;
[self displayCount];
}
- (IBAction)minus:(UIButton*)sender {
count--;
if (negative){ //This simply checks if negative mode is offsw_rear
if (count < 0){ //and if count is negative
count = 0; //sets it back to zero
}}
[self displayCount];
}
- (void)displayCount {
[self.countLabel setText:[[NSString alloc]initWithFormat:#"%ld", (long)self.count]];
}
- (UIViewAnimationOptions) closeAnimationCurve {
return UIViewAnimationOptionCurveEaseOut;
}
// Enabling Deepnes on left menu
- (BOOL)deepnessForLeftMenu
{
return YES;
}
// Enabling Deepnes on left menu
- (BOOL)deepnessForRightMenu
{
return YES;
}
// Enabling darkness while left menu is opening
- (CGFloat)maxDarknessWhileLeftMenu
{
return 0.50;
}
// Enabling darkness while right menu is opening
- (CGFloat)maxDarknessWhileRightMenu
{
return 0.5;
}
#end
Suppose, you have made multiple selections in your main Table.
Then using [mainTable indexPathsForSelectedRows]; will give the indexPaths of the selected cells.
Before you go to next View Controller, pass a array containing selected cells using :
1.) Create a new array in which you loop through these indexPath.row and get the elements from cupcakes Array.
NSMutableArray *selectedCellArray = [[NSMutableArray alloc] init];
for(NSIndexPath *index in [mainTable indexPathsForSelectedRows])
{
[selectedCellArray addObject: cupcakes[index.row]];
}
2.) Pass this to your next View Controller by creating a array property in it.
viewController.tableArray = selectedCellArray;

how to pass the NSMutableArray to UITableView

data values i have one text filed and two buttons.One button is save,second button is show.
when click save button data will be Stored in Core-Data and then i click Show button data will be displayed on Console. It gone nice.
But now i want when Click show button data will be displayed on UITableView So Please Give me any idea
Thanks in advanced,
this is my code:-
#import "SetViewController.h"
#import "AppDelegate.h"
#interface SetViewController ()
{
NSMutableArray *array;
}
#end
#implementation SetViewController
#synthesize textField;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)save:(id)sender {
AppDelegate *appD=(AppDelegate *) [[UIApplication sharedApplication]delegate];
NSEntityDescription *entit=[NSEntityDescription insertNewObjectForEntityForName:#"Team" inManagedObjectContext:appD.managedObjectContext];
[entit setValue:textField.text forKey:#"fname"];
NSError *error;
BOOL isSaved=[appD.managedObjectContext save:&error];
NSLog(#"succesfully saved flag: %d",isSaved);
}
- (IBAction)show:(id)sender {
AppDelegate *appDelegat=(AppDelegate*)[[UIApplication sharedApplication]delegate];
NSEntityDescription *entity=[NSEntityDescription entityForName:#"Team" inManagedObjectContext:appDelegat.managedObjectContext];
NSFetchRequest *fetchRr = [[NSFetchRequest alloc]init];
[fetchRr setEntity:entity];
array=[[appDelegat.managedObjectContext executeFetchRequest:fetchRr error:nil]mutableCopy];
NSLog(#"array %#",array);
for (NSManagedObject *obj in array) {
NSLog(#"Name :%#\n",[obj valueForKey:#"fname"]);
}
}
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
[textField resignFirstResponder];
return YES;
}
#end
i am tried like this :-
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([segue.identifier isEqualToString:#"ShowData"])
{
ShowViewController *destViewController = segue.destinationViewController;
destViewController.second = [[array valueForKey:#"fname"] componentsJoinedByString(angry)" , "];
NSLog(#" got data for array %#",destViewController.second);
}
}
ShowViewController.h:-
#import <UIKit/UIKit.h>
#import "SetViewController.h"
#interface ShowViewController : UITableViewController<UITableViewDelegate,UITableViewDataSource>
#property (nonatomic, strong) NSString *second;
#end
ShowViewController.m:-
import "ShowViewController.h"
#interface ShowViewController ()
{
NSMutableArray *acess;
}
#end
#implementation ShowViewController
#synthesize second;
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
acess =[second componentsSeparatedByString:#", "];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [acess count];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (!cell)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] ;
}
cell.textLabel.text = [acess objectAtIndex:indexPath.row];
return cell;
}
ShowViewController is UITableView.When Click UItableView is open but data will be not Displayed So Please give me any idea
Follow following steps and also read programming guide of UITableview provided by apple:
After getting the array just reload your table view.
Make number of rows = array count.
Customize the cell as per your need.
If you only declared the array as per you shown in code then you must need to initialise it in view did load like this:
array=[NSMutablearray array];
after that get the values from db and stored in array an use UITable view delegate and datasource methods.
First declare your array in your viewDidload() method.
- (void)viewDidLoad
{
yourArray=[[NSArray alloc]initWithObjects:Obj1,obj2,obj3,obj4,obj5, nil];
}
and then use tableview delegate methods. to set array data to tableview.
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
return [yourArray count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"Cell" forIndexPath:indexPath];
// Configure the cell...
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"Cell"];
}
cell.textLabel.text=[yourArray objectAtIndex:indexPath.row];
return cell;
}
If you already have an NSArray that contains your strings, there is no need to go through the whole componentsJoinedByString/componentsSeparatedByString - you can just pass the array to your second view controller.
Accessing the passed data in viewDidLoad won't work though because when you set the property in prepareForSegue the view has already loaded.
Your prepareForSegue should be -
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([segue.identifier isEqualToString:#"ShowData"])
{
ShowViewController *destViewController = (ShowViewController *)segue.destinationViewController;
destViewController.fnames = [array valueForKey:#"fname"];
}
}
In your .h file for ShowViewController declare a property to receive frames -
#property (strong,nonatomic) NSArray *fnames;
Then your table data source methods will be -
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [self.fnames 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] ;
}
cell.textLabel.text = [self.fnames objectAtIndex:indexPath.row];
return cell;
}

Identifying and then loading/reloading a specific tableView

I have a viewcontroller set up on my storyboard, and I have inserted a tableView inside this view controller. I want to do a [self.tableView reloadData].
This is what my viewController.m looks like. My tableView is an IBOutlet called sharedView, hence the names in the methods, but I am doing something wrong as on viewDidLoad when I call configureView, and subsequently [self.sharedView reloadData]; the data doesn't show up inside the table.
#import "DetailViewController.h"
#import "sharedUsersTable.h"
#interface DetailViewController ()
- (void)configureView;
#end
#implementation DetailViewController
#pragma mark - Managing the detail item
- (void)setDetailItem:(id)newDetailItem
{
if (_detailItem != newDetailItem) {
_detailItem = newDetailItem;
// Update the view.
[self configureView];
}
}
- (void)configureView
{
// Update the user interface for the detail item.
if (self.detailItem) {
self.detailDescriptionLabel.text = [[self.detailItem objectForKey:#"lock_name"] description];
activeUsers = [self.detailItem objectForKey:#"active_shared_users"];
[self.sharedView reloadData];
//NSLog(#"Info: %#", activeUsers);
}
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[self configureView];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
-(NSString *)sharedView:(UITableView *)sharedView titleForHeaderInSection:(NSInteger)section {
return #"Shared with";
}
- (NSInteger)sharedView:(UITableView *)sharedView numberOfRowsInSection:(NSInteger)section
{
return activeUsers.count;
}
- (sharedUsersTable *)sharedView:(UITableView *)sharedView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"sharedUser";
sharedUsersTable *cell = [sharedView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[sharedUsersTable alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
NSDictionary *key;
NSString *name;
NSString *email;
// NSString *permission;
key = [activeUsers objectAtIndex:indexPath.row];
name = [key objectForKey:#"shared_user_name"];
email = [key objectForKey:#"email"];
NSLog(#"Info: %#", name);
cell.textLabel.text = [NSString stringWithFormat:#"%#", name];
cell.detailTextLabel.text = [NSString stringWithFormat:#"%#", email];
return cell;
}
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
// Return NO if you do not want the specified item to be editable.
return YES;
}
#end
You should add info about protocols that Your VC is implementing:
#interface DetailViewController () <UITableViewDataSource, UITableViewDelegate>
- (void)configureView;
#end
and then:
- (void)configureView
{
// Update the user interface for the detail item.
if (self.detailItem) {
self.detailDescriptionLabel.text = [[self.detailItem objectForKey:#"lock_name"] description];
activeUsers = [self.detailItem objectForKey:#"active_shared_users"];
/* I assume that Your table view is self.sharedView though You should change the name and I assume that it is connected to VC */
self.sharedView.dataSource = self;
self.sharedView.delegate = self;
[self.sharedView reloadData];
//NSLog(#"Info: %#", activeUsers);
}
}
You can also set data source and delegate directly in storyboard - I think that You have to ctrl+drag from table view to vc. Sorry if this is not correct - I do not use IB for quite some time no - only code.
And one more thing - read this:
https://developer.apple.com/library/ios/documentation/UIKit/Reference/UITableViewDataSource_Protocol/Reference/Reference.html#//apple_ref/occ/intf/UITableViewDataSource
And change method names to be exactly the same as in the protocol - If You do not It won't work.
For better undesstanding data sources and delegates try:
https://developer.apple.com/library/ios/documentation/userexperience/conceptual/tableview_iphone/CreateConfigureTableView/CreateConfigureTableView.html
You mentioned that you are using a UIViewController and not UITableViewController. If you are using UIViewController then you will need to implement UITableViewDelegate and UITableViewDataSourceDelegate. You will also need to connect those delegates either through code or using the interface builder or Storyboard.

Get Object attributes in tableviewcontroller

I'm just going to be crazy. I want to display some attributes from an object in a TableViewController.
To resume :
I've got a first screen with a list of different Aircraft. Each Aircraft is different and get 2 attributes (a name and an identification number). When i click on an aircraft i want to display its informations in a new view controller (here a TableViewController).
The only thing i get is an empty string... I don't understand how to do this.
Here my code for AircraftViewController.h (the list of different aircraft)
#import <UIKit/UIKit.h>
#import "AircraftInfoViewController.h"
#interface AircraftViewController : UITableViewController <AircraftInfoViewControllerDelegate>
#property (nonatomic, strong) NSMutableArray *aircraft;
#end
Here my code for AircraftViewController.m
#import "AircraftViewController.h"
#import "Aircraft.h"
#interface AircraftViewController ()
#end
#implementation AircraftViewController
{
NSString *_info;
}
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
return [self.aircraft count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
AircraftCell *cell = (AircraftCell *)[tableView dequeueReusableCellWithIdentifier:#"AircraftCell"];
Aircraft *aircraft = (self.aircraft)[indexPath.row];
cell.immatLabel.text = aircraft.immat;
return cell;
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([segue.identifier isEqualToString:#"PickInfo"]) {
AircraftInfoViewController *aircraftInfoViewController = segue.destinationViewController;
aircraftInfoViewController.delegate = self;
aircraftInfoViewController.info = _info;
}
}
- (void)aircraftInfoViewController:(AircraftInfoViewController *)controller didSelectInfo:(NSString *)info
{
_info = info;
Aircraft *aircraft = [[Aircraft alloc] init];
// Here is my problem !
NSLog(#"String is %#", aircraft.name);
[self.navigationController popViewControllerAnimated:YES];
}
#end
Here my Aircraft Object
#import <Foundation/Foundation.h>
#interface Aircraft : NSObject
#property (nonatomic, copy) NSString *name;
#property (nonatomic, copy) NSString *immat;
#end
Here my AircraftInfoViewController.h (where i display info)
#class AircraftInfoViewController;
#protocol AircraftInfoViewControllerDelegate <NSObject>
- (void)aircraftInfoViewController:(AircraftInfoViewController *)controller didSelectInfo:(NSString *)info;
#end
#interface AircraftInfoViewController : UITableViewController
#property (nonatomic, weak) id <AircraftInfoViewControllerDelegate> delegate;
#property (nonatomic, strong) NSString *info;
#end
Here my AircraftInfoViewController.m
#import "AircraftInfoViewController.h"
#interface AircraftInfoViewController ()
#end
#implementation AircraftInfoViewController
{
NSArray *_infos;
NSUInteger _selectedIndex;
}
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
_infos = #[#"TEST"];
_selectedIndex = [_infos indexOfObject:self.info];
}
// self.navigationItem.rightBarButtonItem = self.editButtonItem;
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [_infos count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"AircraftCell"];
cell.textLabel.text = _infos[indexPath.row];
if (indexPath.row == _selectedIndex) {
cell.accessoryType = UITableViewCellAccessoryCheckmark;
} else {
cell.accessoryType = UITableViewCellAccessoryNone;
}
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[tableView deselectRowAtIndexPath:indexPath animated:YES];
if (_selectedIndex != NSNotFound) {
UITableViewCell *cell = [tableView cellForRowAtIndexPath:
[NSIndexPath indexPathForRow:_selectedIndex inSection:0]];
cell.accessoryType = UITableViewCellAccessoryNone;
}
_selectedIndex = indexPath.row;
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
cell.accessoryType = UITableViewCellAccessoryCheckmark;
NSString *info = _infos[indexPath.row];
[self.delegate aircraftInfoViewController:self didSelectInfo:info];
}
#end
Thx for helping...
I don't exactly get your problem, but in your code you are:
//1. creating a new aircraft
Aircraft *aircraft = [[Aircraft alloc] init];
//2. this aircraft object is new and dose not have a name yet as you never assigned a name to it.
//3. this is why your log shows an empty string
NSLog(#"String is %#", aircraft.name);
Looks like you need to print the info:
NSLog(#"String is %#", _info);
But it will be helpful to help you if you could explain what you want to get better.

UITableView as subview is always empty

I have a ViewController which has several subviews (Graphs) added using function
[self.view addSubview:subView]
Now, I want to add a UITableView as subview, but when I do this, my table is always empty. Methods like numberOfSectionsInTableView, numberOfRowsInSection, etc are never called.
My table doesn't have a XIB file. This is the code from my .M file:
#import "TableSubviewViewController.h"
#implementation TableSubviewViewController
#synthesize data;
#synthesize tableFrame;
-(id)initWithStyle:(UITableViewStyle)style{
self = [super initWithStyle:style];
if (self) {
// Custom initialization
}
return self;
}
-(void)viewDidLoad{
[super viewDidLoad];
self.view.frame = tableFrame;
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
return [[self.data allKeys]count];
}
-(NSString*)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
return [[self.data allKeys]objectAtIndex:section];
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return 1;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
if(cell == nil){
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
cell.textLabel.text = #"Some text";
return cell;
}
And this is the code in my main ViewController, in which I'm creating TableSubviewViewController:
TableSubviewViewController *tableSubView = [[TableSubviewViewController alloc]initWithStyle:UITableViewStyleGrouped];
tableSubView.tableFrame = tableFrame;
tableSubView.data = data;
[self.view addObject:tableSubView.view];
What Am I missing?
Thank you
TableSubviewViewController tableSubView must be main ViewController's global variable , can't be a local variable in the method viewDidLoad of main ViewController
U need to set datasource and delegate methods do like this
// in TableSubviewViewController.h file put a custom initilizer
#interface TableSubviewViewController : UIViewController
- (id)initTheSubviewTableVIewWithFrame:(CGRect)rect; //your custom initialiser
#end
//TableSubviewViewController.m file
#import "TableSubviewViewController.h"
#interface TableSubviewViewController ()<UITableViewDataSource,UITableViewDelegate>
#end
#implementation TableSubviewViewController
//dont use this method left blank
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialisation
}
return self;
}
//you can make custom initiliser method
- (id)initTheSubviewTableVIewWithFrame:(CGRect)rect
{
self = [super init];
if(self)
{
UITableView *subViewTable = [[UITableView alloc]initWithFrame:rect];//since u are creating the tableview programatically u need to set datasource and delegate programatically
subViewTable.dataSource = self; //add this
subViewTable.delegate = self; //this also
[self.view addSubview:subViewTable];
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
//datasource and delegate methods
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
return 2;
}
//use as reqired
//-(NSString*)tableView:(UITableView *)tableView titleForHeaderInSection: (NSInteger)section{
// return 3;
//}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return 1;
}
-(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 = #"Some text";
return cell;
}
//in main ViewController.m controler u need to do like this
TableSubviewViewController *subViewTable = [[TableSubviewViewController alloc]initTheSubviewTableVIewWithFrame:CGRectMake(self.view.bounds.origin.x, self.view.bounds.origin.y, self.view.bounds.size.width, 150)];//created the subviewTableView tableview
//set properties that u defined for tableview delegate and datasource
[self.view addSubview:subViewTable.view];
hope this helps u :)
Make sure your .h file use
and set delegate and datasource to self.
TableSubviewViewController *tableSubView = [[TableSubviewViewController alloc]initWithStyle:UITableViewStyleGrouped];
tableSubView.tableFrame = tableFrame;
tableSubView.delegate = self;
tableSubView.dataSource = self;
tableSubView.data = data;
[self.view addObject:tableSubView.view];
After that check whether array self.data have object or not. It might be possible that array is blank.

Resources