I have a problem. At the moment I'm polishing my app and debug it and so on. Something weird happened. Here is how it works: User enters data and gets to the TableView and the data gets displayed. Simple. But as soon as he switches to another view and then back to the TableView, the data is gone! The weird thing is that it didnt happen before. (I redid some codelines, maybe I changed something unknowingly). I have a hinch what it might be, but it would be weird because it worked before. The problem I think lies at the buttonTag line:
- (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.image = selectedImage;
cell.textLabel.font = [UIFont fontWithName:#"Georgia" size:14.0];
if (buttonTag == 9001) {
cell.textLabel.text = [NSString stringWithFormat:#"%# %# %#, %#.", [self.userData objectAtIndex:0], [self.userData objectAtIndex:1], [self.userData objectAtIndex:2], [self.userData objectAtIndex:3]];
}
if (buttonTag == 9002) {
cell.textLabel.text = [NSString stringWithFormat:#"%# %# %#, %#.", [self.userData objectAtIndex:0], [self.userData objectAtIndex:1], [self.userData objectAtIndex:2], [self.userData objectAtIndex:3]];
}
if (buttonTag == 9003) {
cell.textLabel.text = [NSString stringWithFormat:#"%# %# %#,%#.", [self.userData objectAtIndex:0], [self.userData objectAtIndex:1], [self.userData objectAtIndex:2], [self.userData objectAtIndex:3]];
}
return cell;
}
Because he just displays the data when a particular button is pressed. If you change to the TableView without pressing one of those buttons (From a Tabbar e.g.) it doesnt show anything. My question is now: How can I tell the TableView to maintan the data from the last button pressed? (I was thinking NSUserDefaults?)
Here is another ViewController, the one from where you get to the TableView:
- (IBAction)savePressed:(id)sender
{
if (buttonTag == 9001) {
button.tag = 9001;
NSUserDefaults *savetext = [NSUserDefaults standardUserDefaults];
[savetext setObject:Antwort.text forKey:#"hallo"];
[savetext setObject:Antwort2.text forKey:#"hallo2"];
[savetext setObject:Antwort3.text forKey:#"hallo3"];
UIButton *buttonPressed = (UIButton *)sender;
TV *second =[[TV alloc] initWithNibName:nil bundle:nil];
second.buttonTag = buttonPressed.tag;
[self.navigationController pushViewController:second animated:YES];
}
if (buttonTag == 9002) {
button.tag = 9002;
NSUserDefaults *savetext = [NSUserDefaults standardUserDefaults];
[savetext setObject:Antwort.text forKey:#"hallo"];
[savetext setObject:Antwort2.text forKey:#"hallo2"];
[savetext setObject:Antwort3.text forKey:#"hallo3"];
UIButton *buttonPressed = (UIButton *)sender;
TV *second =[[TV alloc] initWithNibName:nil bundle:nil];
second.buttonTag = buttonPressed.tag;
[self.navigationController pushViewController:second animated:YES];
}
if (buttonTag == 9003) {
button.tag = 9003;
NSUserDefaults *savetext = [NSUserDefaults standardUserDefaults];
[savetext setObject:Antwort.text forKey:#"hallo"];
[savetext setObject:Antwort2.text forKey:#"hallo2"];
[savetext setObject:Antwort3.text forKey:#"hallo3"];
UIButton *buttonPressed = (UIButton *)sender;
TV *second =[[TV alloc] initWithNibName:nil bundle:nil];
second.buttonTag = buttonPressed.tag;
[self.navigationController pushViewController:second animated:YES];
}
}
If the data is read & saved in NSUSerDefaults, try
[savetext synchronize]
before pushing to new view.
Related
I am new to objective C. I have a checkbox (its a image) inside a table view. when ever this checkbox is clicked i want get the row (table row id) of the clicked check box.
My application looks like this
objective c
I tried like this but it always gives me the first id
- (void)checkBoxBtnPressed:(id)sender {
UIButton *btn = (UIButton *)sender;
PickupTicketsItemObject *item = [ticketList objectAtIndex:btn.tag];
NSLog(#"item_select %#", item.getTicket_id);
if ([item isSelected]) {
[btn setBackgroundImage:[UIImage imageNamed:#"icon_uncheck"] forState:UIControlStateNormal];
[item setIsSelected:NO];
}else {
[btn setBackgroundImage:[UIImage imageNamed:#"icon_check"] forState:UIControlStateNormal];
[item setIsSelected:YES];
}
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
NSLog(#"selected index : %#", indexPath);
NSLog(#"selected index : %ld", (long)indexPath.section);
//Check if assigned to user
PickupTicketsItemObject *item = [ticketList objectAtIndex:indexPath.section];
NSLog(#"selected index : %#", item.ticket_id);
NSLog(#"selected index : %#", item.ticket_assignedto);
//Print all user defaults key and value
//NSLog(#"%#", [[NSUserDefaults standardUserDefaults] dictionaryRepresentation]);
// get the display name from user defaults
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
NSString *displayName;
NSString *AgentName;
if ([userDefaults objectForKey:#"DisplayName"] != nil) {
displayName = [userDefaults objectForKey:#"DisplayName"];
}else { displayName = #"Not defined"; }
AgentName = [#"Agent : " stringByAppendingString:displayName];
NSLog(#"Display Name : %#", displayName);
NSLog(#"Agent Name : %#", AgentName);
NSLog(#"Assigned Name : %#", item.ticket_assignedto);
// ticket is already assigned to agent, send to ticket details page
if ([item.ticket_assignedto isEqualToString:AgentName]) {
NSLog(#"Ticket already assigned to this User.");
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:#"Main" bundle:nil];
TicketDetailViewController *ticketDetailViewController = [storyboard instantiateViewControllerWithIdentifier:#"TicketDetailViewController"];
ticketDetailViewController.ticket_id = item.ticket_id;
[kNavigationController pushViewController:ticketDetailViewController animated:YES];
[kMainViewController hideLeftViewAnimated:YES completionHandler:nil];
} else{
NSLog(#"Ticket not assigned to this User.");
// Ask the user to pick the ticket.
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:#"Main" bundle:nil];
SinglePickUpViewController *singlePickUpViewController = [storyboard instantiateViewControllerWithIdentifier:#"SinglePickupVC"];
singlePickUpViewController.ticket_id = item.ticket_id;
[kNavigationController pushViewController:singlePickUpViewController animated:YES];
[kMainViewController hideLeftViewAnimated:YES completionHandler:nil];
}
}
Can some one help me to get the clicked checkboxes table row id. tnx
If you have only one section,
PickupTicketsItemObject *item = [ticketList objectAtIndex:indexPath.section];
always gives you the first element. Try:
PickupTicketsItemObject *item = [ticketList objectAtIndex:indexPath.row];
Please try this it may help you.
In cellForRowAtIndexPath method write this:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
btn.tag = indexPath.row + 100;
}
And in your button action method:
- (void)checkBoxBtnPressed:(id)sender {
UIButton *btn = (UIButton *)sender;
NSInteger rowId = btn.tag - 100;
}
I have an array of dictionaries in NSUserDefaults and those values are used to display data in a table view in another tab on the tab bar. It works ok if I add a new value to my NSUserDefaults array and close the app then go back into it and go the table view tab. The problem I'm having is when I add a new object to the user defaults array then go to the table view tab without leaving the app. When I do this, the table view does not show the just added values.
Here is where I add the dictionaries to NSUserDefaults:
- (void)addFavorite {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSMutableArray *favoritesLoaded = [defaults objectForKey:#"favorites"];
NSDictionary *fav = [NSDictionary dictionaryWithObjectsAndKeys:
self.postTitle, #"title",
self.postUrlString, #"url",
nil];
NSMutableArray *favorites = [NSMutableArray array];
if (favoritesLoaded) {
favorites = [[NSMutableArray alloc] initWithArray:favoritesLoaded];
} else {
favorites = [[NSMutableArray alloc] init];
}
[favorites insertObject:fav atIndex:0];
[defaults setObject:favorites forKey:#"favorites"];
[defaults synchronize];
}
In my table view:
- (void)viewDidLoad {
[super viewDidLoad];
self.navigationItem.rightBarButtonItem = self.editButtonItem;
[self.tableView setDataSource:self];
[self.tableView setDelegate:self];
self.tableView.backgroundColor = [UIColor blackColor];
if ([[NSUserDefaults standardUserDefaults] objectForKey:#"favorites"]) {
self.redditPosts = [[NSUserDefaults standardUserDefaults] objectForKey:#"favorites"];
}
else {
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
CustomCell *cell = [tableView dequeueReusableCellWithIdentifier:#"CustomCell"];
NSDictionary *post = [self.redditPosts objectAtIndex:[indexPath row]];
if (cell == nil) {
cell = [[CustomCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"CustomCell"];
}
if (cell) {
cell.textLabel.text = [post objectForKey:#"title"];
cell.backgroundColor = [UIColor clearColor];
cell.textLabel.textColor = [UIColor whiteColor];
}
return cell;
}
just after inserting your new content you should reload the tableView:
[self.tableView reloadData];
if this can take a while you can use the following so it won't freeze-up your app:
dispatch_async(dispatch_get_main_queue(), ^{
[self.tableView reloadData];
});
I have an existing UITableView that lists a number of cafes in the area. The data for each cafe is being pulled from a MySQL database. When a user clicks on a cafe (cell), it brings a user to a detail view. Currently, users can "Favorite" a cafe by clicking on the star image in each cell (this adds the favorited cell to FavoritesTableView). However, I want users to be able to add a cafe to the FavoritesTableView from the DetailView as well (in other words, "favorite" a cafe from the DetailView). Does anyone know how I would implement this?
Right now, I have the star button in place in my DetailView.m (cafe details):
- (IBAction)buttonpressed:(UIButton *)fave {
if (!checked) {
[checkedButton setImage:[UIImage imageNamed:#"checked.png"] forState:UIControlStateNormal];
checked = YES;
}
else if (checked) {
[checkedButton setImage:[UIImage imageNamed:#"unchecked.png"] forState:UIControlStateNormal];
checked = NO;
}
}
ViewController.m (cafes tableview)
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *strainTableIdentifier = #"StrainTableCell";
StrainTableCell *cell = (StrainTableCell *)[tableView dequeueReusableCellWithIdentifier:strainTableIdentifier];
if (cell == nil)
cell = [[StrainTableCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:strainTableIdentifier];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
cell.selectionStyle = UITableViewCellSelectionStyleBlue;
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"StrainTableCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
if (tableView == self.searchDisplayController.searchResultsTableView) {
NSLog(#"Using the search results");
cell.titleLabel.text = [[searchResults objectAtIndex:indexPath.row] objectForKey:#"Title"];
cell.descriptionLabel.text = [[searchResults objectAtIndex:indexPath.row] objectForKey:#"Description"];
cell.ratingLabel.text = [[searchResults objectAtIndex:indexPath.row] objectForKey:#"Rating"];
cell.ailmentLabel.text = [[searchResults objectAtIndex:indexPath.row] objectForKey:#"Ailment"];
cell.actionLabel.text = [[searchResults objectAtIndex:indexPath.row] objectForKey:#"Action"];
cell.ingestLabel.text = [[searchResults objectAtIndex:indexPath.row] objectForKey:#"Ingestion"];
NSLog(#"%#", searchResults);
} else {
NSLog(#"Using the FULL LIST!!");
cell.titleLabel.text = [[Strains objectAtIndex:indexPath.row] objectForKey:#"Title"];
cell.descriptionLabel.text = [[Strains objectAtIndex:indexPath.row] objectForKey:#"Description"];
cell.ratingLabel.text = [[Strains objectAtIndex:indexPath.row] objectForKey:#"Rating"];
cell.ailmentLabel.text = [[Strains objectAtIndex:indexPath.row] objectForKey:#"Ailment"];
cell.actionLabel.text = [[Strains objectAtIndex:indexPath.row] objectForKey:#"Action"];
cell.ingestLabel.text = [[Strains objectAtIndex:indexPath.row] objectForKey:#"Ingestion"];
}
NSMutableDictionary *item = [Strains objectAtIndex:indexPath.row];
cell.textLabel.text = [item objectForKey:#"text"];
[item setObject:cell forKey:#"StrainTableCell"];
BOOL checked = [[item objectForKey:#"checked"] boolValue];
NSLog(#"%i",checked);
UIImage *image = (checked) ? [UIImage imageNamed:#"checked.png"] : [UIImage imageNamed:#"unchecked.png"];
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
CGRect frame = CGRectMake(0.0, 0.0, image.size.width, image.size.height);
button.frame = frame;
[button setBackgroundImage:image forState:UIControlStateNormal];
[button addTarget:self action:#selector(checkButtonTapped:event:) forControlEvents:UIControlEventTouchUpInside];
button.backgroundColor = [UIColor clearColor];
cell.accessoryView = button;
return cell;
}
- (void)checkButtonTapped:(id)sender event:(id)event
{
NSLog(#"made it here and event is %#",event);
NSSet *touches = [event allTouches];
UITouch *touch = [touches anyObject];
CGPoint currentTouchPosition = [touch locationInView:self.StrainTableView];
NSIndexPath * indexPath ;
indexPath = [self.StrainTableView indexPathForRowAtPoint: currentTouchPosition];
NSLog(#"indexpath is below");
NSLog(#"%#",indexPath);
if (indexPath != Nil)
{
NSMutableDictionary *item = [Strains objectAtIndex:indexPath.row];
BOOL isItChecked = [[item objectForKey:#"checked"] boolValue];
NSMutableArray *quickArray = [[NSMutableArray alloc] initWithArray:Strains];
[quickArray replaceObjectAtIndex:indexPath.row withObject:item];
[item setObject:[NSNumber numberWithBool:!isItChecked] forKey:#"checked"];
Strains = [quickArray copy];
[StrainTableView reloadData];
}
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
StrainDetailViewController *detailViewController = [[StrainDetailViewController alloc] initWithNibName:#"StrainDetailViewController" bundle:nil]; if ([searchResults count]) {
detailViewController.title = [[searchResults objectAtIndex:indexPath.row] objectForKey:#"Title"];
detailViewController.strainDetail = [searchResults objectAtIndex:indexPath.row];
} else {
detailViewController.title = [[Strains objectAtIndex:indexPath.row] objectForKey:#"Title"];
detailViewController.strainDetail = [Strains objectAtIndex:indexPath.row];
NSLog(#"%#", Strains);
}
[self.navigationController pushViewController:detailViewController animated:YES];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
if ([[NSUserDefaults standardUserDefaults] objectForKey:#"strains"] != Nil) {
NSData *dataSave = [[NSUserDefaults standardUserDefaults] objectForKey:#"strains"];
Strains = [NSKeyedUnarchiver unarchiveObjectWithData:dataSave];
}
if (favoritesArray == Nil) {
favoritesArray = [[NSMutableSet alloc] init];
}
if ([[NSUserDefaults standardUserDefaults] objectForKey:#"favorites"] != Nil) {
NSData *dataSave = [[NSUserDefaults standardUserDefaults] objectForKey:#"favorites"];
favoritesArray = [NSKeyedUnarchiver unarchiveObjectWithData:dataSave];
}
I'm just not sure what sort of code I would add to this in order to make the "Checked" button add the selected cell from UITableView to FavoritesTableView.
Hope this made sense. Any ideas?
From a maintainability stand point, the approach I generally take might not be the best. However, from an implementation stand point, it's very easy. I pass a reference to my object (in your case, the object for the table view that was selected) to the details view. From the details view, I can update that object by switching the flag. Since this object is the same object as the table view, updating it will also update the table view (you may have to redraw the table view cell). Last, I update the database from the details view.
Edit
So in your code, it would look like this.
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
StrainDetailViewController *detailViewController = [[StrainDetailViewController alloc] initWithNibName:#"StrainDetailViewController" bundle:nil]; if ([searchResults count]) {
detailViewController.title = [[searchResults objectAtIndex:indexPath.row] objectForKey:#"Title"];
//YOU'RE ALREADY DOING IT :)
detailViewController.strainDetail = [searchResults objectAtIndex:indexPath.row];
} else {
detailViewController.title = [[Strains objectAtIndex:indexPath.row] objectForKey:#"Title"];
//YOU'RE ALREADY DOING IT :)
detailViewController.strainDetail = [Strains objectAtIndex:indexPath.row];
NSLog(#"%#", Strains);
}
[self.navigationController pushViewController:detailViewController animated:YES];
}
You're already sending a reference to the details view! This makes things easy. In your details view, whenever someone favorites a strain, set the favorite flag for the strainDetail object. This will also update the strainDetail object in the table view. It works like this because you're passing a reference (also referred to as a pointer) to the detail view. In other words, both of your strainDetail objects, aren't objects but pointers to a memory address. If you update either strainDetail, the the memory address for both strainDetail gets changed. Not the strainDetail pointer itself. Here's an link for further explanation https://softwareengineering.stackexchange.com/questions/17898/whats-a-nice-explanation-for-pointers
So your Details view handler will look something like this
- (IBAction)buttonpressed:(UIButton *)fave {
if (!checked) {
[checkedButton setImage:[UIImage imageNamed:#"checked.png"] forState:UIControlStateNormal];
checked = YES;
}
else if (checked) {
[checkedButton setImage:[UIImage imageNamed:#"unchecked.png"] forState:UIControlStateNormal];
checked = NO;
}
//updates in both the detail view and the table view
BOOL isItChecked = [[self.strainDetail objectForKey:#"checked"] boolValue];
[self.strainDetail setObject:[NSNumber numberWithBool:checked] forKey:#"checked"];
}
I also suggest creating a Strain class to hold all of your strain data. Working with dictionaries is not fun, is error prone, and takes forever to figure out what keys you need.
You can save "favorite" state in a global variable/singleton and retrieve it when needed.
This way, even if your table view is deallocated, you won't lose its cells' state.
I have a ChatViewController where I send and receive messages and store the messages as a NSMutableDictionary in an NSArray.
NSMutableArray *messages; //in header file
- (void)addMessage:(NSString *)receivedMessage :(NSString *) sender
{
[self reloadDataInTableView:receivedMessage :sender];
}
- (void)reloadDataInTableView:(NSString *)message :(NSString*)sender
{
NSLog(#"Text: %# Sender: %#", message, sender);
NSMutableDictionary *m = [[NSMutableDictionary alloc] init];
[m setObject:message forKey:#"msg"];
[m setObject:sender forKey:#"sender"];
[messages addObject:m];
[self.tView reloadData];
NSLog(#"Number of rows: %d", [messages count]);
}
When I am calling 'addMessage' from AppDelegate, both the strings are passed but it cannot add it to the 'messages' because the 'Number of rows' always is zero. But when I am storing it from that class itself then the messages are getting stored and row count increases.
As a result, it only shows the messages from the ChatViewController but not the messages sent from the AppDelegate. I hope I was able to explain the problem properly.
Here is the cellForRowAtIndexPath function:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSMutableDictionary *s = (NSMutableDictionary *) [messages objectAtIndex:indexPath.row];
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
//cell = [[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier];
}
cell.textLabel.text = [s objectForKey:#"msg"];
cell.detailTextLabel.text = [s objectForKey:#"sender"];
cell.accessoryType = UITableViewCellAccessoryNone;
cell.userInteractionEnabled = NO;
return cell;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [messages count];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
Yes, I have initialized the messages array in viewDidLoad. But the problem is when I am trying to insert into the messages array from the AppDelegate the count is not increasing. In fact, it always shows zero. But when I insert from the ViewController itself, it maintains the count. Here is the AppDelegate code:
- (void)xmppStream:(XMPPStream *)sender didReceiveMessage:(XMPPMessage *)message
{
if ([message isChatMessageWithBody])
{
XMPPUserCoreDataStorageObject *user = [xmppRosterStorage userForJID:[message from]
xmppStream:xmppStream
managedObjectContext:[self managedObjectContext_roster]];
NSString *messageBody = [[message elementForName:#"body"] stringValue];
NSString *displayName = [user jidStr];
if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateActive)
{
ChatViewController *cvc = [[ChatViewController alloc] init];
[cvc reloadDataInTableView:messageBody :displayName];
}
else
{
// We are not active, so use a local notification instead
UILocalNotification *localNotification = [[UILocalNotification alloc] init];
localNotification.alertAction = #"Ok";
localNotification.alertBody = [NSString stringWithFormat:#"From: %#\n\n%#",displayName,messageBody];
[[UIApplication sharedApplication] presentLocalNotificationNow:localNotification];
}
}
}
When you do
ChatViewController *cvc = [[ChatViewController alloc] init];
[cvc reloadDataInTableView:messageBody :displayName];
in your app delegate, you are instantiating a new ChatViewController. Even if the messages array was initialised in the init method (which it isn't, as you said it is initialised in the viewDidLoad method), this new instance of the ChatViewController is discarded at the end of your xmppStream:didReceiveMessage: method and is definitely not the same that is showing on screen.
You need to keep a reference to the proper instance of ChatViewController in your app delegate and use that instead of instantiating a new one...
If you want some more specific advice on how to approach this problem, you'll need to give us more detail about your whole project's architecture (using storyboard? is there a navigation controller? tab controller? how does the chatviewcontroller relate to other view controllers? etc. etc.).
You need
messages = [[NSMutableArray alloc] init];
in viewdidload
Try this:
- (void)reloadDataInTableView:(NSString *)message :(NSString*)sender
{
NSLog(#"Text: %# Sender: %#", message, sender);
NSMutableDictionary *m = [[NSMutableDictionary alloc] init];
[m setObject:message forKey:#"msg"];
[m setObject:sender forKey:#"sender"];
if (!messages)
{
messages = [[NSMutableArray alloc] init];
}
[messages addObject:m];
[self.tView reloadData];
NSLog(#"Number of rows: %d", [messages count]);
}
I am inserting NSMutableArray(self.tablePdfListArray) in tableview textlabel and NSMutableArray(self.dateListArray) in detailtextlabel at same index. It got added correctly at first place but when I am opening the TableView again the detailTextlabel becoming textlabel and textlabel is becoming detailTextlabel.
I have NSLog both the NSMutabelArray and come to know that both array value are getting swap. How to retain its original values? Thanks in advance for any suggestion.
Edited With tableView code
- (void)viewDidLoad
{
if([[NSUserDefaults standardUserDefaults] objectForKey:#"children"] != nil )
{
self.tablePdfListArray = [NSMutableArray arrayWithArray:[[NSUserDefaults standardUserDefaults] objectForKey:#"children"]];
}
if ([[NSUserDefaults standardUserDefaults] objectForKey:#"dates"] != nil)
{
self.dateListArray = [NSMutableArray arrayWithArray:[[NSUserDefaults standardUserDefaults] objectForKey:#"dates"]];
}
}
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
if (buttonIndex == 0)
{
self.myPDFName = [NSString stringWithFormat:#"%#", [alertView textFieldAtIndex:0].text];
firstDayInYear = [NSDate date];
dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setTimeStyle:NSDateFormatterShortStyle];
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
NSString *currentTime = [dateFormatter stringFromDate:firstDayInYear];
NSLog(#"User's current time in their preference format:%#",currentTime);
if(!self. tablePdfListArray)
{
self.tablePdfListArray = [[NSMutableArray alloc]init];
}
if(!self.dateListArray)
{
self.dateListArray = [[NSMutableArray alloc]init];
}
[self.dateListArray insertObject:currentTime atIndex:0];
NSLog(#"mhy date dateListArray %#",dateListArray);
//the below if condition will not allow repeatative string array in tableList and textfield lenth.
if ([[alertView textFieldAtIndex:0].text length] != 0 && ![self.tablePdfListArray containsObject:self.myPDFName])
{
[self.tablePdfListArray insertObject:[NSString stringWithFormat:#"%#", [alertView textFieldAtIndex:0].text] atIndex:0];
NSLog(#"mhy date tablePdfListArray %#",tablePdfListArray);
NSIndexPath * indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
[self.pdfListnameTable insertRowsAtIndexPaths:#[indexPath]withRowAnimation:UITableViewRowAnimationAutomatic];
NSUserDefaults *defaults=[NSUserDefaults standardUserDefaults];
[defaults setObject:self.dateListArray forKey:[NSString stringWithFormat:#"children"]];
[defaults setObject:self.tablePdfListArray forKey:[NSString stringWithFormat:#"dates"]];
[defaults synchronize];
}
}}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
if( tableView == pdfListnameTable)
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
cell.selectionStyle = UITableViewCellSelectionStyleNone; //cell bg
//self.myChklist.backgroundColor = [UIColor clearColor];
}
NSString *tablePdfname = [self.tablePdfListArray objectAtIndex:indexPath.row];
cell.textLabel.text = tablePdfname;
NSString *tablePdfdate = [self.dateListArray objectAtIndex:indexPath.row];
//[dateFormatter setTimeStyle:NSDateFormatterMediumStyle];
cell.detailTextLabel.text = tablePdfdate;
return cell;
}
}
Why are you checking tableView == pdfListnameTable ?
That should be tableView isEqual:self. pdfListnameTable. Not sure that is relevant here, but if you have more than one tableView - i'd guess that you aren't switching to it as there seems to be a lack of an else statement for that.
Well, I'm not sure but I did a little refactoring of your code. You have some places where it looks like you're trying to access a property, but then you're also trying to access it as an instance value.
So, here is what I did. It may not be correct. but it should be close (or at least will help you figure this out)
#interface someTableViewController()
#property(nonatomic, strong) NSMutableArray *tablePdfListArray;
#property(nonatomic, strong) NSMutableArray *dateListArray;
#property(nonatomic, copy) NSString *myPDFName;
#property(nonatomic, strong) NSDate *firstDayInYear;
#property(nonatomic, strong) NSDateFormatter *dateFormatter;
#property(nonatomic, weak) IBOutlet UITableView *pdfListnameTable;
#end
#implementation someTableViewController
-(void)viewDidLoad {
self.tablePdfListArray = [NSMutableArray new];
self.dateListArray = [NSMutableArray new];
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
if([userDefaults objectForKey:#"children"] != nil ) {
self.tablePdfListArray = [NSMutableArray arrayWithArray:[[NSUserDefaults standardUserDefaults] objectForKey:#"children"]];
}
if([userDefaults objectForKey:#"dates"] != nil) {
self.dateListArray = [NSMutableArray arrayWithArray:[[NSUserDefaults standardUserDefaults] objectForKey:#"dates"]];
}
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
cell.selectionStyle = UITableViewCellSelectionStyleNone; //cell bg
NSInteger currentRow = indexPath.row;
NSString *tablePdfname = [self.tablePdfListArray objectAtIndex:currentRow];
cell.textLabel.text = tablePdfname;
NSString *tablePdfdate = [self.dateListArray objectAtIndex:currentRow];
cell.detailTextLabel.text = tablePdfdate;
UIButton *someButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 44, 44)];
[someButton setTitle:#"CLICK" forState:UIControlStateNormal];
[someButton addTarget:self action:#selector(testButtonClickIndexPath:) forControlEvents:UIControlEventTouchUpInside];
[cell.contentView addSubview:someButton];
return cell;
}
-(void)testButtonClickIndexPath:(id)sender {
CGPoint touchPoint = [sender convertPoint:CGPointZero toView:self.pdfListnameTable];
NSIndexPath *indexPath = [self.pdfListnameTable indexPathForRowAtPoint:touchPoint];
if(indexPath != nil) {
// show alert message, call it, or whatever. just using a silly one for now..
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"RAR"
message:#"Mamma Say..my..my mamma say"
delegate:self
cancelButtonTitle:#"Medulla Oblongata"
otherButtonTitles:#[ #"h2o", #"Gatorade"]];
[alert show];
}
}
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
if(buttonIndex == 0) {
self.myPDFName = [NSString stringWithFormat:#"%#", [alertView textFieldAtIndex:0].text];
self.firstDayInYear = [NSDate date];
self.dateFormatter = [[NSDateFormatter alloc] init];
[self.dateFormatter setTimeStyle:NSDateFormatterShortStyle];
[self.dateFormatter setDateStyle:NSDateFormatterMediumStyle];
NSString *currentTime = [self.dateFormatter stringFromDate:self.firstDayInYear];
NSLog(#"User's current time in their preference format:%#",currentTime);
[self.dateListArray insertObject:currentTime atIndex:0];
NSLog(#"mhy date dateListArray %#",self.dateListArray);
//the below if condition will not allow repeatative string array in tableList and textfield lenth.
if([[alertView textFieldAtIndex:0].text length] != 0 && ![self.tablePdfListArray containsObject:self.myPDFName]) {
[self.tablePdfListArray insertObject:[NSString stringWithFormat:#"%#", [alertView textFieldAtIndex:0].text] atIndex:0];
NSLog(#"mhy date tablePdfListArray %#",self.tablePdfListArray);
NSIndexPath * indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
[self.pdfListnameTable insertRowsAtIndexPaths:#[indexPath]withRowAnimation:UITableViewRowAnimationAutomatic];
NSUserDefaults *defaults=[NSUserDefaults standardUserDefaults];
[defaults setObject:self.dateListArray forKey:[NSString stringWithFormat:#"dates"]];
[defaults setObject:self.tablePdfListArray forKey:[NSString stringWithFormat:#"children"]];
[defaults synchronize];
}
}
}
#end