update UITableViewCell from other method - ios

i have search thousand in GG to find solution update data to UITableViewCell but all show me the solution is
UITableViewCell *cell=(UITableViewCell*)[self.tableView cellForRowAtIndexPath:indexPath];
but the cell is nil for all cells that are visible. I have use NSNotification to send data from one method to ViewController.m , and the Reiever method i want update data to cell by indexPath. but all cell is nil and cannt not update that.
here my code
ViewController.h
#import <UIKit/UIKit.h>
#interface ViewController : UIViewController <UITableViewDelegate, UITableViewDataSource>
#property(nonatomic, strong) IBOutlet UITableView *tableView;
#end
ViewController.m
#implementation ViewController
{
}
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[[NSNotificationCenter defaultCenter]addObserver:self selector:#selector(theReciever:) name:#"theSender" object:nil];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [recipes count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *simpleTableIdentifier = #"SimpleTableCell";
UITableViewCell* cell = [self.tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
NSLog(#"cell nil");
}
NSString *idgame=#"Gamexyz";
cell.textLabel.text = idgame;
cell.tag=indexPath.row;
return cell;
}
-(void)theReciever:(NSNotification*)notif{
if([notif.object isKindOfClass:[packeData class]]){
packeData *data=[notif object];
NSString *key=data.key;
NSInteger *index=[key integerValue];
NSIndexPath *indexPath=[NSIndexPath indexPathWithIndex:index];
UITableViewCell *cell=(UITableViewCell*)[self.tableView cellForRowAtIndexPath:indexPath];
//UITableViewCell *cell=(UITableViewCell*)[self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:7 inSection:0]];
if(cell==nil)
{
NSLog(#"cell NULL");
}else{
cell.textLabel.text=data.process;
}
}else{
NSLog(#"ERR: object not recognised");
}
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
any one can help me or solution example for update data in UITableViewCell by indexPath

NOTE: below is just an example u can do it in new project
One thing u need to change the data model packeData, lets say it contains key as NSIntager which holdes the index of the cell and process is NSString which holds the progress as string value for example
in packeData.h
#import <Foundation/Foundation.h>
#interface packeData : NSObject
#property (nonatomic, assign) NSInteger key; //holds index
#property (nonatomic, strong) NSString *process; //holds the progress info
#end
and in packeData.m
#import "packeData.h"
#implementation packeData
- (id)init //simply initialise it
{
self = [super init];
if(self)
{
}
return self;
}
#end
and in view controller where u are tableview,
in ViewController.h
#import <UIKit/UIKit.h>
#import "packeData.h"
#interface ViewController : UIViewController <UI TableViewDataSource,UITableViewDelegate>
#property (weak, nonatomic) IBOutlet UITableView *aTableView;
#property (strong,nonatomic) NSMutableArray *recipes; //array acts as datasource
#end
in in ViewController.m
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[[NSNotificationCenter defaultCenter]addObserver:self selector:#selector(theReciever:) name:#"theSender" object:nil];
_recipes = [[NSMutableArray alloc]init]; //initilise your datasource
for(int j = 0 ;j< 20;j++)
{
// for my example i took some values
//initially put some initial values
packeData *data = [[packeData alloc] init];
data.key = j;
data.process = [NSString stringWithFormat:#"game_name_%d",j];
[_recipes addObject:data];
}
}
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
[NSTimer scheduledTimerWithTimeInterval:0.8 target:self selector:#selector(PostNotification) userInfo:nil repeats:YES]; //just for testing
}
- (void)PostNotification
{
//i am simply posting the notification with some random values
packeData *data = [[packeData alloc]init];
data.key = arc4random()%15;
data.process = [NSString stringWithFormat:#"%ld",( data.key + 20)];
[[NSNotificationCenter defaultCenter] postNotificationName:#"theSender" object:data];
}
- (void)theReciever:(NSNotification *)notif
{
if([notif.object isKindOfClass:[packeData class]]){
packeData *data=[notif object];
NSInteger key=data.key;
NSInteger index= key;
//modify the datasource
packeData *recipes_data = [_recipes objectAtIndex:index]; //get the pocket present in array
recipes_data.process = data.process; //modify the recipes data
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:index inSection:0];
UITableViewCell *cell=(UITableViewCell*)[self.aTableView cellForRowAtIndexPath:indexPath];
if(cell==nil)
{
NSLog(#"cell NULL");
}else
{
[self.aTableView reloadRowsAtIndexPaths:#[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
// cell.textLabel.text=data.process; no need u already mofied the content in the datasource this will call the "cellForRowAtIndexPath" method and displays the process in place of game name
}
}else{
NSLog(#"ERR: object not recognised");
}
}
- (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 [_recipes count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *simpleTableIdentifier = #"SimpleTableCell";
UITableViewCell* cell = [self.aTableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
NSLog(#"cell nil");
}
packeData *idgame= [_recipes objectAtIndex:indexPath.row];
cell.textLabel.text = idgame.process; //initially contains game name
cell.tag=indexPath.row;
return cell;
}
#end
EDIT
replace the below methods
- (void)PostNotification
{
//i am simply posting the notification with some random values
packeData *data = [[packeData alloc]init];
data.key = arc4random()%15; //15 change the number of rows
data.process = [NSString stringWithFormat:#"%ld",( data.key + arc4random() % 100)];
[[NSNotificationCenter defaultCenter] postNotificationName:#"theSender" object:data];
}
- (void)theReciever:(NSNotification *)notif
{
if([notif.object isKindOfClass:[packeData class]]){
packeData *data=[notif object];
NSInteger key=data.key;
NSInteger index= key;
//modify the datasource
packeData *recipes_data = [_recipes objectAtIndex:index]; //get the pocket present in array
recipes_data.process = data.process; //modify the recipes data
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:index inSection:0];
UITableViewCell *cell=(UITableViewCell*)[self.aTableView cellForRowAtIndexPath:indexPath];
if(cell==nil)
{
NSLog(#"cell NULL");
[self.aTableView reloadData]; //if cell is not visible then reload the whole table
}else
{
[self.aTableView reloadRowsAtIndexPaths:#[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
// cell.textLabel.text=data.process; no need u already mofied the content in the datasource this will call the "cellForRowAtIndexPath" method and displays the process in place of game name
}
}else{
NSLog(#"ERR: object not recognised");
}
}
Edit 2
as for testing just change the below method and as soon as simulator launches the app scroll to down so that only top 5 rows only updates, wait for 5 to 10 seconds and scroll to top and u will see all the calls are updates with same process 5
//scroll down as soon as launches the app and wait for 5 to 10 seconds then scroll to top u will see top 5 cells are updates with progress 5
- (void)PostNotification
{
packeData *data = [[packeData alloc]init];
data.key = arc4random()%5; //only top 5 cells are modify other wont modify
data.process = [NSString stringWithFormat:#"%ld",5];//updates with some same progress lates give it as 5 //( data.key + arc4random() % 100)];
[[NSNotificationCenter defaultCenter] postNotificationName:#"theSender" object:data];
}
form the above test u will see the top 5 cells are updates even when they are not visible

You can't set the value of any of your cell's controller apart from cellForRowAtIndexPath you have to populate the UITableViewCell data with an array, then when you want to update the data in your cell, update your array according to data, then update the single cell of your UITableView like this.
[tableView beginUpdates];
[tableView reloadRowsAtIndexPaths:#[indexPathOfYourCell] withRowAnimation:UITableViewRowAnimationNone];
[tableView endUpdates];

Just specify your index path of your row and reload...
NSIndexPath* path = [NSIndexPath indexPathForRow:3 inSection:0];
NSArray* rowsToReload = [NSArray arrayWithObjects:path, nil];
[tableView reloadRowsAtIndexPaths:rowsToReload withRowAnimation:UITableViewRowAnimationNone];

Related

How to filter the multiple selected values from an array and load it to other uitableview from a uibutton

I have 2 UiTableviews in a UiViewController. My exact requirement is to get the selected values from tableview1 and loaded to the tableview2 by tapping the Add Button.
I done Following at the moment
1. loaded JSON Responses to tableview1 (loaded the responses from a filepath at the moment) and printed to a custom nib cell
2. I can get the selected values to a response as follows
Next
3. I want to print that values to *cell2 from the selected values. Please explain the next steps in details.
Here is the UI
Main UI and Description
Here are the codes from table loading to selections.
Object - PSAData.h
#interface PSAData : NSObject
#property (nonatomic, strong) NSString *firstname;
#property (nonatomic, strong) NSString *lastname;
- (void)loadWithDictionary:(NSDictionary *)dict;
#end
Object - PSAData.m
#implementation PSAData
- (void)loadWithDictionary:(NSDictionary *)dict
{
self.firstname=[dict objectForKey:#"firstname"];
self.lastname=[dict objectForKey:#"lastname"];
}
table1 Viewcell - PSATableViewCell.h
#import <UIKit/UIKit.h>
#import "PSAData.h"
#import "NetworkConnectivityClass.h"
#interface PSATableViewCell : UITableViewCell
#property (nonatomic) NetworkConnectivityClass *networkConnectivityClassInstance;
-(void)loadWithData:(PSAData *)psaData;
#end
table1 viewcell - PSATableViewCell.m
#interface PSATableViewCell ()
#property (strong, nonatomic) IBOutlet UILabel *firstnameLbl;
#property (strong, nonatomic) IBOutlet UILabel *lastnameLbl;
#end
#implementation PSATableViewCell
- (void)awakeFromNib {
[super awakeFromNib];
// Initialization code
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
[super setSelected:selected animated:animated];
}
-(void)loadWithData:(PSAData *)psaData
{
[self methodSetupText:psaData];
}
-(void)methodSetupText:(PSAData *)psaData
{
self.firstnameLbl.text=psaData.firstname;
self.lastnameLbl.text=psaData.lastname;
}
#end
Main View Controller - PersonnelViewController
- (void)viewDidLoad {
[super viewDidLoad];
// NSMutableArray *selectedArray=[[NSMutableArray alloc]init];
tableView1.dataSource =self;
tableView1.delegate=self;
tableView2.dataSource=self;
tableView2.delegate=self;
//initializing arrays for get selected values
self.selectedCells=[NSMutableArray array];
self.selectedPSAData=[NSMutableArray array];
//loading web resonse data
self.loadedPSAData=[[NSMutableArray alloc]init];
NetworkConnectivityClass *networkConnectivityClassInstance = [NetworkConnectivityClass new];
__weak PersonnelViewController *weakVersionOfSelf=self;
[networkConnectivityClassInstance methodReturnTableViewMessages:^(NSMutableArray *returnedArrayWithMessages)
{
weakVersionOfSelf.loadedPSAData=returnedArrayWithMessages;
[weakVersionOfSelf.tableView1 reloadData];
}];
//register left side tableview cell (Assigned tableview1)
[self.tableView1 registerNib:[UINib nibWithNibName:#"PSATableViewCell" bundle:nil] forCellReuseIdentifier:#"PSATableViewCell"];
}
//tableview Delegates
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
if(tableView ==self.tableView1)
{
return 1;
}
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
if(tableView==self.tableView1)
{
return self.loadedPSAData.count;
}
return self.loadedPSAData.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
//loading table data into cell tableview1 and tableview2
static NSString *cellIdentifier=#"PSATableViewCell";
PSATableViewCell *cell=[tableView1 dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell==nil) {
cell=[[PSATableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"PSATableViewCell"];
}
//tableview2 implementation
static NSString *cellIdentifier2=#"PSSITableViewCell";
PSSITableViewCell *cell2=[tableView2 dequeueReusableCellWithIdentifier:cellIdentifier2];
if (cell2==nil) {
cell2=[[PSSITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"PSSITableViewCell"];
}
cell.accessoryType = ([self isRowSelectedOnTableView:tableView1 atIndexPath:indexPath]) ? UITableViewCellAccessoryCheckmark : UITableViewCellAccessoryNone;
if(tableView == self.tableView1)
{
[cell loadWithData:[self.loadedPSAData objectAtIndex:[indexPath row]]];
}
else if(tableView == self.tableView2)
{
[cell2 loadWithDataS2:[self.loadedPSAData objectAtIndex:[indexPath row]]];
return cell2;
}
return cell;
}
pragma mark - multiple selection
- (void)tableView:(UITableView *)tableView
didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
NSString *psaData =[self.loadedPSAData objectAtIndex:indexPath.row];
PSATableViewCell *cell=[tableView1 cellForRowAtIndexPath:indexPath];
NSString *sampleAH =[self.selectedPSAData description];
if([self isRowSelectedOnTableView:tableView1 atIndexPath:indexPath])
{
[self.selectedCells removeObject:indexPath];
[self.selectedPSAData removeObject:psaData];
cell.accessoryType =UITableViewCellAccessoryNone;
}
else{
[self.selectedCells addObject:indexPath];
[self.selectedPSAData addObject:psaData];
cell.accessoryType =UITableViewCellAccessoryCheckmark;
}
NSLog(#"%#", self.selectedPSAData);
sampleArrayholder.text=[NSString stringWithFormat:#"%#", sampleAH];
}
-(BOOL)isRowSelectedOnTableView:(UITableView *)tableView atIndexPath:(NSIndexPath *)indexPath
{
return ([self.selectedCells containsObject:indexPath]) ? YES : NO;
}
**Finally NetworkConnectivity class - NetworkConnectivityClass.h **
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
#import "WorksitenameList.h"
#interface NetworkConnectivityClass : NSObject
-(void)methodLogin:(NSString *)stringToLogin withUserName:(NSString *)stringUsername withPassword:(NSString *)stringPassword completion:(void(^)(NSDictionary *))completion;
-(void)methodReturnTableViewMessages:(void (^)(NSMutableArray *))completion;
-(NSURLSessionTaskState)methodCheckIfSessionIsRunning;
-(void)methodCancelNetworkRequest;
#end
**Finally NetworkConnectivity class - NetworkConnectivityClass.m **
-(void)methodReturnTableViewMessages:(void (^)(NSMutableArray *))completion
{
dispatch_queue_t queueForJSON = dispatch_queue_create("queueForJSON", NULL);
dispatch_async(queueForJSON, ^{
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"PSAData" ofType:#"json"];
NSError *error = nil;
NSData *rawData = [NSData dataWithContentsOfFile:filePath options:NSDataReadingMappedIfSafe error:&error];
id JSONData = [NSJSONSerialization JSONObjectWithData:rawData options:NSJSONReadingAllowFragments error:&error];
NSMutableArray *loadedPSAData = [NSMutableArray new];
[loadedPSAData removeAllObjects];
if([JSONData isKindOfClass:[NSDictionary class]])
{
NSArray *loadedArray=[JSONData objectForKey:#"records"];
if([loadedArray isKindOfClass:[NSArray class]])
{
for(NSDictionary *psaDict in loadedArray)
{
PSAData *psaData=[[PSAData alloc]init];
[psaData loadWithDictionary:psaDict];
[loadedPSAData addObject:psaData];
}
}
}
dispatch_async(dispatch_get_main_queue(), ^{
completion(loadedPSAData);
NSLog(#"test: %#", loadedPSAData);
});
});
}
I Added All the required codes to have a look at it. Since I am relatively new to iOS Dev. Please Write a codes / instructions step by step clearly to save some time :).
**Please Note : At the moment I loaded the same tableview1 data to tableview2 *cell2 But I want here to load the selected values(Multiple Selection). from tableview1 loadedPSAData Array to load in table view to by tapping an Add Button. Finally sorry for my poor English ;) **
Suppose these 2 are your table outlet.
__weak IBOutlet UITableView * myTable1;
__weak IBOutlet UITableView * myTable2;
You set the Delegate and Data Source like below in your viewDidLoad
myTable1.delegate=self;
myTable1.dataSource=self;
myTable2.delegate=self;
myTable2.dataSource=self;
Now These are 2 Arrays
array1 ==> Which contain All Data
arraySelectedValues ==> Which contain you selected data
So you use this like below
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if(self.myTable1 == tableView)
{
return [array1 count];
} else {
return [arraySelectedValues count];
}
}
As I review your Code, Your problem may be in CellForRow. Why to create 2 separate cells, when there is same CellIdentifier. You just need to change the Data.
You should create 2 cells only When Both Tableview are using Diff-Diff tableviewcells. In your case you are using same cell.
Try to modify the code like this
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *cellIdentifier=#"PSATableViewCell";
PSATableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell==nil) {
cell=[[PSATableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier: cellIdentifier];
}
if(tableView == myTable1)
{
[cell loadWithData:[array1 objectAtIndex:[indexPath row]]];
}
else if(tableView == myTable2)
{
[cell loadWithData:[arraySelectedValues objectAtIndex:[indexPath row]]];
}
return cell;
}
didSelectRowAtIndexPath should look like :
- (void)tableView:(UITableView *)tableView
didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
if(tableView == myTable1)
{
// Your code for highlighting
} else {
// This will be you myTable2 did select click.
}
}
Just When ever you want to refresh the record, you should to Call ReloadData method For respective Tableviews.
Hope you understand how you load the data in 2 Tableviews in Single ViewController.

How to get UISearchBar to always stay inside the NavigationBar

I need the UISearchBar to always stay inside the NavigationBar. But so far self.searchDisplayController.displaysSearchBarInNavigationBar = YES; is not doing it. When I first start the app the searchBar is inside the NavigationBar. But as soon as I click on it, it smacks itself right in the middle of my scene/screen and never leaves.
This question is a follow up to How do I add storyboard-based Header and CustomTableCell to a “Search Bar and Search Display Controller”
My .h file is
#import <UIKit/UIKit.h>
#interface ViewController : UIViewController <UISearchDisplayDelegate, UITableViewDataSource, UITableViewDelegate>
#end
and my .m file is
#import "ViewController.h"
#interface ViewController ()
#property(nonatomic,strong)NSMutableArray *data;
#end
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.searchDisplayController.displaysSearchBarInNavigationBar = YES;
self.data=[[NSMutableArray alloc]init];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)aTableView {
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)aTableView numberOfRowsInSection:(NSInteger)section {
// Return the number of rows in the section.
return [_data count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"CellIdentifier";
// Dequeue or create a cell of the appropriate type.
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] ;
cell.accessoryType = UITableViewCellAccessoryNone;
}
// Configure the cell.
cell.textLabel.text = [NSString stringWithFormat:#"Row %d", indexPath.row];
cell.textLabel.text = [NSString stringWithFormat:#"Row %d: %#", indexPath.row, [_data objectAtIndex:indexPath.row]];
return cell;
}
#pragma mark - delegate
- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString
{
[NSTimer scheduledTimerWithTimeInterval:2 target:self selector:#selector(mockSearch:) userInfo:searchString repeats:NO];
return NO;
}
- (void)mockSearch:(NSTimer*)timer
{
[_data removeAllObjects];
int count = 1 + random() % 20;
for (int i = 0; i < count; i++) {
[_data addObject:timer.userInfo];
}
[self.searchDisplayController.searchResultsTableView reloadData];
}
#end
And that’s the entire program.

Trouble with Custom UITableViewCells and UITableView

I have implemented a Twitter feed in a UITableViewController and I'm using a custom cell with a UITextView in it so it has link detection. The problem I'm having is that only the first cell shows up and if I start scrolling the app crashes with EXC_BAD_ACCESS on cell.tweetText.text = t[#"text"];. The feed shows up correctly if I don't use a custom cell, but then you can't tap on a link.
TweetCell.h
#import <UIKit/UIKit.h>
#interface TweetCell : UITableViewCell <UITextViewDelegate>
#property (weak, nonatomic) IBOutlet UITextView *tweetText;
#end
tableviewcontroller.h
#import <UIKit/UIKit.h>
#interface GRSTwitterTableViewController : UITableViewController
#property (nonatomic, strong) NSMutableArray *twitterFeed;
#end
tableviewcontroller.m
#import "GRSTwitterTableViewController.h"
#import "TweetCell.h"
#import "STTwitter.h"
#interface GRSTwitterTableViewController ()
#end
#implementation GRSTwitterTableViewController
#synthesize twitterFeed;
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
self.title = #"";
self.tableView = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStyleGrouped];
UIBarButtonItem *openTwitterButton = [[UIBarButtonItem alloc]initWithTitle:#"Open in Twitter" style:UIBarButtonItemStylePlain target:self action:#selector(openTwitter:)];
self.navigationItem.rightBarButtonItem = openTwitterButton;
STTwitterAPI *twitter = [STTwitterAPI twitterAPIAppOnlyWithConsumerKey:#"xz9ew8UZ6rz8TW3QBSDYg" consumerSecret:#"rm8grg0aIPCUnTpgC5H1NMt4uWYUVXKPqH8brIqD4o"];
[twitter verifyCredentialsWithSuccessBlock:^(NSString *username)
{
[twitter getUserTimelineWithScreenName:#"onmyhonorband" count:50 successBlock:^(NSArray *statuses)
{
twitterFeed = [NSMutableArray arrayWithArray:statuses];
[self.tableView reloadData];
}
errorBlock:^(NSError *error)
{
NSLog(#"%#", error.debugDescription);
}];
}
errorBlock:^(NSError *error)
{
NSLog(#"%#", error.debugDescription);
}];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)openTwitter:(id)sender
{
NSURL *twitterURL = [NSURL URLWithString:#"twitter:///user?screen_name=onmyhonorband"];
NSURL *safariURL = [NSURL URLWithString:#"https://twitter.com/onmyhonorband"];
if ([[UIApplication sharedApplication]canOpenURL:twitterURL])
{
[[UIApplication sharedApplication]openURL:twitterURL];
}
else
{
[[UIApplication sharedApplication]openURL:safariURL];
}
}
#pragma mark - Table view data source
- (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 [twitterFeed count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
tableView.backgroundColor = [UIColor darkGrayColor];
TweetCell *cell = [tableView dequeueReusableCellWithIdentifier:#"myCell"];
if (!cell)
{
[tableView registerNib:[UINib nibWithNibName:#"TweetCell" bundle:nil] forCellReuseIdentifier:#"myCell"];
cell = [tableView dequeueReusableCellWithIdentifier:#"myCell"];
}
NSInteger idx = indexPath.row;
NSDictionary *t = twitterFeed[idx];
cell.tweetText.text = t[#"text"];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[tableView deselectRowAtIndexPath:indexPath animated:YES];
}
#end
Here is a screenshot of what the tableview looks like when using the custom cell.
replace the line code
TweetCell *cell = [tableView dequeueReusableCellWithIdentifier:#"myCell"];
if (!cell)
{
[tableView registerNib:[UINib nibWithNibName:#"TweetCell" bundle:nil] forCellReuseIdentifier:#"myCell"];
cell = [tableView dequeueReusableCellWithIdentifier:#"myCell"];
}
with the below code
TweetCell *cell = [tableView dequeueReusableCellWithIdentifier:#"myCell"];
if (!cell)
{
NSArray *nibs =[[NSBundle mainBundle] loadNibNamed:#"TweetCell" owner:self options:NULL];
cell = [nibs firstObject];
}

Passing data from dynamic tableview back to static tableview

Please help i have been struggling passing back the data. I have 2 tableViews. 1st tableview=static table=RootVC. 2nd tableview=dynamic table=FirstVC. in RootVC i have a cell with two labels, "repeatLabel" and "repeatDetail" with a disclosure indicator. When i click on the cell it display the next table which is FirstVC, FistVC is populated with weekdays. after selection of my choice, i want the selected days to be passed back into RootVC in "repeatDetail" and when i go back still be able to see previously selected data.
My RootVC looks like this:
#import "RepeatViewController.h"
#interface SettingsViewController : UITableViewController
#property (strong, nonatomic) IBOutlet UILabel *repeatDetail;
#property (strong, nonatomic) IBOutlet UILabel *repeatLabel;
#property (strong,nonatomic) NSString *getRepeatDetail;
#property (nonatomic, strong) NSMutableArray *selectedDaysArray;
#end
in my RootVC.m
#import "SettingsViewController.h"
#interface SettingsViewController ()
#end
#implementation SettingsViewController
#synthesize repeatLabel,repeatDetail;
#synthesize getRepeatLabel;
#synthesize selectedDaysArray;
- (void)viewDidLoad
{
[super viewDidLoad];
repeatLabel.text = #"Repeat";
repeatDetail.text = getRepeatLabel;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
RepeatViewController *destinationController = segue.destinationViewController;
if( [destinationController isKindOfClass:[RepeatViewController class]] )
{
//You can reuse your selectedDays arrays
destinationController.selectedDays = self.selectedDaysArray;
[(RepeatViewController *)destinationController setCompletionBlock:^(NSArray *retDaysArray) // <- make this change
{
// Save your changes
self.selectedDaysArray = [NSMutableArray arrayWithArray: retDaysArray]; // <- make this change
NSLog(#"retDaysArray: %#", self.selectedDaysArray); //<- Add this debug line
}];
}
}
#end
My 1stVC.h
#import "SettingsViewController.h"
typedef void(^WeekdayCompletionBlock)(NSArray *retDaysArray);
#interface RepeatViewController : UITableViewController <UITableViewDataSource,UITableViewDelegate>
#property (nonatomic,strong) NSMutableArray *selectedDays;
#property (nonatomic, copy) NSArray *completionBlock;
#property (copy) WeekdayCompletionBlock returnBlock;
//#property (strong, nonatomic) IBOutlet UIBarButtonItem *saveButton;
-(IBAction)save:(id)sender;
#end
my 1stVC.m
#import "RepeatViewController.h"
#interface RepeatViewController ()
#end
#implementation RepeatViewController
#synthesize selectedDays= _selectedDays;
#synthesize completionBlock;
#synthesize returnBlock;
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
completionBlock = [NSArray arrayWithObjects:#"Sunday", #"Monday", #"Tuesday", #"Wednesday", #"Thursday", #"Friday", #"Saturday", nil];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - Table view data source
- (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 7;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellIdentifier = #"RepeatCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellIdentifier];
}
NSString *day = completionBlock[indexPath.row];
cell.textLabel.text = day;
if ([self.selectedDays containsObject:day])
cell.accessoryType = UITableViewCellAccessoryCheckmark;
else
cell.accessoryType = UITableViewCellAccessoryNone;
//cell.textLabel.text = [completionBlock objectAtIndex:indexPath.row];
return cell;
}
#pragma mark - Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
if (!self.selectedDays)
self.selectedDays = [[NSMutableArray alloc] init];
if (cell.accessoryType == UITableViewCellAccessoryCheckmark)
{
cell.accessoryType = UITableViewCellAccessoryNone;
//remove data from array
[self.selectedDays removeObject:[completionBlock objectAtIndex:indexPath.row]];
}
else
{
cell.accessoryType = UITableViewCellAccessoryCheckmark;
//add data to array
[self.selectedDays addObject:[completionBlock objectAtIndex:indexPath.row]];
}
[tableView deselectRowAtIndexPath:indexPath animated:YES];
}
-(IBAction)save:(id)sender
{
NSUserDefaults *myNewWeekString = [NSUserDefaults standardUserDefaults];
[myNewWeekString setObject:self.selectedDays forKey:#"MY_KEY_FOR_ACCESING_DAYSOFWEEK"];
[myNewWeekString synchronize];
//NSLog(#"The selected day/s is %#",self.selectedDays);
if (self.returnBlock)
{
self.returnBlock(self.selectedDays);
}
[self.navigationController popViewControllerAnimated:YES];
// NSLog(#"The selected day/s is %#",self.selectedDays);
// if (self.returnBlock)
// {
// self.returnBlock([completionBlock objectAtIndex:indexPath.row]);
//}
}
/*
-(void) setReturnBlock:(WeekdayCompletionBlock)returnBlock
{
[self.selectedDays addObject:(self.returnArray);
}
- (NSArray *)setDats
{
return [NSArray arrayWithArray:[self.selectedDays copy]];
}*/
#end
When you work with static cells you have to bind the control you are using directly, there's no need.
So what I can suggest you is the following:
Bind your controls with some specific identifier, like labelFieldRow{rowid} example: labelFieldRow1.
So on prepare for segue, just check what's the selected row and pass the data you want to the destination controller.
Probably not the best, but it should work.
You have to pass data (selected by user before) from your RootVC to FirstVC. To do that in your RootVC add property to keep the selected data;
#property (nonatomic, strong) NSMutableArray *selectedDaysArray;
In prepareForSegue method you have to pass that array to let the table view know what needs to be selected:
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
UIViewController *destinationController = segue.destinationViewController;
if( [destinationController isKindOfClass:[RepeatViewController class]] )
{
//You can reuse your selectedDays arrays
((RepeatViewController*)destinationController).selectedDays = self.selectedDaysArray;
[(RepeatViewController *)destinationController setReturnBlock:^(NSArray *retDaysArray) // <- make this change
{
// Save your changes
self.selectedDaysArray = [NSMutableArray arrayWithArray: retDaysArray]; // <- make this change
NSLog(#"DATA: %#", self.selectedDaysArray) //<- Add this debug line
}];
}
}
Remove this line from viewDidLoad you don't want to allocate it every time now you just pass it from rootVC
_selectedDays = [[NSMutableArray alloc] init];
And in cellForRowInIndexPath replace this line:
cell.textLabel.text = [completionBlock objectAtIndex:indexPath.row];
with this code:
NSString *day = completionBlock[indexPath.row];
cell.textLabel.text = day;
if ([self.selectedDays containsObject:day])
cell.accessoryType = UITableViewCellAccessoryCheckmark;
else
cell.accessoryType = UITableViewCellAccessoryNone;
And change didSelectRowAtIndexPath: to
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
if (!self.selectedDays)
self.selectedDays = [[NSMutableArray alloc] init];
if (cell.accessoryType == UITableViewCellAccessoryCheckmark)
{
cell.accessoryType = UITableViewCellAccessoryNone;
//remove data from array
[self.selectedDays removeObject:[completionBlock objectAtIndex:indexPath.row]];
}
else
{
cell.accessoryType = UITableViewCellAccessoryCheckmark;
//add data to array
[self.selectedDays addObject:[completionBlock objectAtIndex:indexPath.row]];
}
[tableView deselectRowAtIndexPath:indexPath animated:YES];
}
Hope this help.

UITableView reloadData doesn't work when change sub object in datasoure.

There are 5 objects in datasoure for example,if the first object is like this:
Obj -> id:1,name:"A"
when I change the object's name to "B";
Obj -> id:1,name:"B"
then [tableView reloadData]
the first cell still display "A",I want to change it to "B".
In the cellForRowAtIndexpath method manage the datasource method properly as it retrives the value from the datasource array and displays it,That is it
I doubt the problem is that the reusability is causing the trouble in your code
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell;
static NSString *cellIdentifier1 = #"surveyCell";
if (tableView== self.surveytableView) {
cell= [tableView dequeueReusableCellWithIdentifier:cellIdentifier1];
if(cell==nil)
{
//alloc the cell
//DO NOT SET THE VALUE HERE
}
//here set the value
return cell;
}
here is the code, what i did was,
created a class called "DataClass" which provides data for your tableview
created objects like you mentioned , i stored it in an array("dataSource")
after that i loaded it to tableview (i assume u are properly wired up tableview datasource and delegate)
I put a button to make change the string in the datasource array.
button's action is connected to method and within that i am reloading the tableview
//class DataClass
#interface DataClass : NSObject
{
#public;
NSString *str;
}
#implementation DataClass
- (id)init
{
[super init];
str = nil;
return self;
}
#end
//viewController.h
#interface ViewController : UIViewController<UITableViewDataSource ,UITableViewDelegate>
{
IBOutlet UITableView *aTableView;
IBOutlet UIButton *aButton;
}
- (IBAction)whenButtonClicked:(id)sender;
#end
//in .m file
#import "ViewController.h"
#import "DataClass.h"
#interface ViewController ()
{
NSMutableArray *DataSource;
}
#end
// ViewController.m
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
aTableView.dataSource = self;
aTableView.delegate = self;
DataSource = [[NSMutableArray alloc]init];
for(int i=0 ; i<5 ; i++)
{
DataClass *data = [[DataClass alloc]init];
data->str=#"hello";
[DataSource addObject:data];
[data release];
}
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *aCell = [tableView dequeueReusableCellWithIdentifier:#"Cell"];
if(aCell == nil)
{
aCell = [[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"Cell"]autorelease];
}
DataClass *aValue = [DataSource objectAtIndex:indexPath.row];
aCell.textLabel.text = aValue->str;
return aCell;
}
- (IBAction)whenButtonClicked:(id)sender
{
DataClass *aObj = [DataSource objectAtIndex:2];//changing the 3'rd object value as yours in 5th object
aObj->str = #"world";
[aTableView reloadData];
}
#end
//after "changeValue" button pressed the third row displays "world"

Resources