Adding and saving data on UITableView - ios

I have a method that is working but its not saving the data that I enter.
This is the code I use to enter data on a
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
if (buttonIndex == 1) {
NSString *tempTextField = [alertView textFieldAtIndex:0].text;
if (!numbers) {
numbers = [[NSMutableArray alloc] init];
}
[[NSUserDefaults standardUserDefaults] setObject:tempTextField forKey:#"Save"];
[numbers insertObject:tempTextField atIndex:0];
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
[self.myTableView insertRowsAtIndexPaths:#[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
} }
It is using a UIAlertView with a plain text input. I try to use an NSUSerDefaults to save the data with the method above and I'm able to retrieve the data on the viewDidLoad with this code
-(void)viewDidLoad {
[super viewDidLoad];
NSArray *siteNameValue = [[NSUserDefaults standardUserDefaults] valueForKey:#"Save"];
numbers = [[NSMutableArray alloc] initWithObjects:siteNameValue, nil];
}
But it would only save one of the data that is entered, it doesnt save multiple data. Any leads?
the variable numbers is an NSMutableArray.

You can store a NSMutableArray object created alertView:clickedButtonAtIndex in the user defaults and reuse it in viewDidLoad:
[numbers insertObject:tempTextField atIndex:0];
[[NSUserDefaults standardUserDefaults] setObject:numbers forKey:#"Save"];
You can get the array with same content in viewDidLoad as follows:
NSMutableArray *numbers = [[[NSUserDefaults standardUserDefaults] arrayForKey:#"Save"] mutableCopy];

Problem is you are saving just one NSString, not a NSArray in NSUserDefaults.
You need to save "numbers" (whole NSArray) instead and also load it as an array (additional encapsulation on loading is not necessary).
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
if (buttonIndex == 1) {
NSString *tempTextField = [alertView textFieldAtIndex:0].text;
if (!numbers) {
numbers = [[NSMutableArray alloc] init];
}
[[NSUserDefaults standardUserDefaults] setObject:numbers forKey:#"Save"];
[numbers insertObject:tempTextField atIndex:0];
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
[self.myTableView insertRowsAtIndexPaths:#[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
}
}
-(void)viewDidLoad {
[super viewDidLoad];
numbers = [[NSUserDefaults standardUserDefaults] valueForKey:#"Save"];
}

Solution
This is the method to ADD and SAVE data on the tableview using a UIALertView plain text style.
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
if (buttonIndex == 1) {
NSString *tempTextField = [alertView textFieldAtIndex:0].text;
if (!numbers) {
numbers = [[NSMutableArray alloc] init];
}
[numbers insertObject:tempTextField atIndex:0];
[[NSUserDefaults standardUserDefaults] setObject:numbers forKey:#"3"];
[[NSUserDefaults standardUserDefaults] synchronize];
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
[self.myTableView insertRowsAtIndexPaths:#[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
}
}
below is to retrieve it under the viewDidLoad
NSMutableArray *siteNameValue = [[[NSUserDefaults standardUserDefaults] arrayForKey:#"3"] mutableCopy];
numbers = siteNameValue;

Related

iOS How to save addButton additions to Master View in Master-Detail Template after quitting app

I have a master-detail program that I add items through a UIAlert to the master list, but when the app quits, the items I added are gone, how can I save the values I added? How would I change to the code below to do this? I've heard you can save to the plist, but I don't know how to use that functionality and I'm not sure its necessary. Thanks!
The value I want to save and reload is "keepValue" which is a NSString property I defined in the header file.
If you are curious how I change the NSDate to a pop up AlertView to add any value you want look here:
- (void)viewDidLoad
{
[super viewDidLoad];
self.navigationItem.leftBarButtonItem = self.editButtonItem;
UIBarButtonItem *addButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd
target:self
action:#selector(insertNewObject:)];
self.navigationItem.rightBarButtonItem = addButton;
}
//modified to pop up alertView see: http://stackoverflow.com/questions/11163341/how-do-i-replace-the-date-with-a-writable-title
- (void)insertNewObject:(id)sender
{
UIAlertView *getTitle = [[UIAlertView alloc] initWithTitle:#"Add Search Keyword" message:nil delegate:self
cancelButtonTitle:#"Add"
otherButtonTitles:nil];
getTitle.alertViewStyle = UIAlertViewStylePlainTextInput;
[getTitle show];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
if (!_objects) {
_objects = [[NSMutableArray alloc] init];
}
NSString * userEnterThisString = [[alertView textFieldAtIndex:0] text];
[_objects insertObject:userEnterThisString atIndex:0];
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
[self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
self.keepValue = userEnterThisString; //Want to keep after app quits
[self.savedSearchValues addObject:self.keepValue]; //trying to save values to reuse?
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"Cell" forIndexPath:indexPath];
NSString *object = _objects[indexPath.row]; //changed here from default NSDate
cell.textLabel.text = [object description];
return cell;
}
Use NSUserDefaults. There are a lot of answers in StackOverflow.
I got a good response on another site, thank you #Robert Bojor. For anyone else curious I added the save data to file portion of the code to the end of the AlertView method, and I added the read it back in the viewDidLoad (both in the Master View)
Here is final code if you are interested:
- (void)viewDidLoad
{
[super viewDidLoad];
self.navigationItem.leftBarButtonItem = self.editButtonItem;
UIBarButtonItem *addButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:#selector(insertNewObject:)];
self.navigationItem.rightBarButtonItem = addButton;
//**********************READ CODE*************************
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
if ([paths count] > 0) {
NSString *addedItems = [[paths objectAtIndex:0] stringByAppendingPathComponent:#"addedItems.dta"];
BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:addedItems];
if (fileExists) {
_objects = [NSArray arrayWithContentsOfFile:addedItems];
} else {
// Notify the user the file doesn't exist or try to load it from a cached resource.
}
}
}
//modified to pop up alertView see: http://stackoverflow.com/questions/11163341/how-do-i-replace-the-date-with-a-writable-title
- (void)insertNewObject:(id)sender {
UIAlertView *getTitle = [[UIAlertView alloc] initWithTitle:#"Add Search Keyword" message:nil delegate:self cancelButtonTitle:#"Add" otherButtonTitles:nil];
getTitle.alertViewStyle = UIAlertViewStylePlainTextInput;
[getTitle show];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
if (!_objects) {
_objects = [[NSMutableArray alloc] init];
}
NSString * userEnterThisString = [[alertView textFieldAtIndex:0] text];
[_objects insertObject:userEnterThisString atIndex:0];
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
[self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:indexPath]withRowAnimation:UITableViewRowAnimationAutomatic];
self.keepValue = userEnterThisString;
//**********************SAVE CODE*************************
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *addedItems = [[paths objectAtIndex:0] stringByAppendingPathComponent:#"addedItems.dta"];
// The file name and extension can be changed at will
[_objects writeToFile:addedItems atomically:YES];
}

Not sure why NSUserdefaults is not saving the results?

I am trying to save checked and remove unchecked tablecells into NSUserdefaults but it seems to ignore it as the NSLog in the for loop never gets called not sure why, is there something wrong with this code? (Everything shows up right and the cells get checked and un-checked correctly)
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
//setting up nsUser
userDefaults = [NSUserDefaults standardUserDefaults];
//current row text
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
NSString *cellName = cell.textLabel.text;
// Check if current row is selected
Boolean isNowChecked = NO;
if([tableView cellForRowAtIndexPath:indexPath].accessoryType == UITableViewCellAccessoryCheckmark)
{
isNowChecked = YES;
}
if(isNowChecked)
{
NSLog(#"UNCHECKING");
[tableView cellForRowAtIndexPath:indexPath].accessoryType = UITableViewCellAccessoryNone;
//takes away highlight from selection
[tableView deselectRowAtIndexPath:indexPath animated:YES];
//retrieve from nsdefaults
NSMutableArray *arrayOfCategories = [userDefaults objectForKey:#"categories"];
NSMutableArray *categoriesSelected;
//remove from nsuserdefaults
//add to nsuserdefaults
for (NSString* o in arrayOfCategories)
{
NSLog(#"%#",o);
if([o isEqualToString:cellName]) {
} else {
[categoriesSelected addObject:o];
}
}
//set for nsdefaults
[userDefaults setObject:categoriesSelected forKey:#"categories"];
[userDefaults synchronize];
}
else
{
NSLog(#"CHECKING");
[tableView cellForRowAtIndexPath:indexPath].accessoryType = UITableViewCellAccessoryCheckmark;
//takes away highlight from selection
[tableView deselectRowAtIndexPath:indexPath animated:YES];
NSMutableArray *categoriesSelected;
//add to array
[categoriesSelected addObject:cellName];
//retrieve from nsdefaults
NSMutableArray *arrayOfCategories = [userDefaults objectForKey:#"categories"];
//add to nsuserdefaults
for (NSString* o in arrayOfCategories)
{
NSLog(#"%#",o);
[categoriesSelected addObject:o];
}
//set for nsdefaults
[userDefaults setObject:categoriesSelected forKey:#"categories"];
[userDefaults synchronize];
}
}
Change this line, otherwise you have an uninitialized Array:
NSMutableArray *categoriesSelected;
to:
NSMutableArray *categoriesSelected = [[NSMutableArray alloc] init];
Update: After looking at your code there are actually quite a few things that should be improved.
You should load the list of checked categories once in viewDidLoad and keep the list in an instance variable.
It's not a good idea to check to see if a cell is currently checked or not by looking at the cell's accessory type. Your data model should tell you which rows are checked.
You have a lot of duplicate code to toggle the checked state of a cell.
Use a set, not an array, to keep track of the checked cells.
Try the following changes:
Add an NSMutableSet instance variable to your class:
NSMutableSet *_checkedCategories;
In viewDidLoad, load the set:
NSArray *checkedCategories = [[NSUserDefault standardUserDefaults] objectForKey:#"categories"];
if (checkedCategories) {
_checkedCategories = [[NSMutableSet alloc] initWithArray:checkedCategories];
} else {
_checkedCategories = [[NSMutableSet alloc] init];
}
Now update your didSelectRow method:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *cellName = ...; // get the cell name from your data model, not the cell
BOOL isChecked = [_checkedCategories containsObject:cellName];
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
if (isChecked) {
[_checkedCategories removeObject:cellName]; // no longer checked
cell.accessoryType = UITableViewCellAccessoryNone;
} else {
[_checkedCategories addObject:cellName]; // now checked
cell.accessoryType = UITableViewCellAccessoryCheckmark;
}
[tableView deselectRowAtIndexPath:indexPath animated:YES];
[[NSUserDefaults standardUserDefaults] setObject:[_checkedCategories allObjects] forKey:#"categories"];
[[NSUserDefaults standardUserDefaults] synchronize];
}

Deleting Rows From Table View | NSUserDefaults + NSKeyedArchiver

- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
myFavsTwo = [NSMutableArray arrayWithArray:[NSKeyedUnarchiver unarchiveObjectWithData:[[[NSUserDefaults standardUserDefaults] objectForKey:#"MyFavoritez"] mutableCopy]]];
[self.tableView reloadData];
NSLog(#"Number of items in my array is: %d", [myFavsTwo count]);
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
NSLog(#"Number of items in my array is: %d", indexPath.row+1);
[myFavsTwo removeObjectAtIndex:indexPath.row];
[self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
[[NSUserDefaults standardUserDefaults] setObject:[NSKeyedArchiver archivedDataWithRootObject:myFavsTwo] forKey:#"MyFavoritez"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
on delete my app keeps crashing at:
[[NSUserDefaults standardUserDefaults] setObject:[NSKeyedArchiver
archivedDataWithRootObject:myFavsTwo] forKey:#"MyFavoritez"];
if I 'continue' on my debugging it still works as it should and everything continues like normal...
not getting any error messages either just a 'break point' message
my view will appear looks like this:
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
myFavsTwo = [NSKeyedUnarchiver unarchiveObjectWithData:[[[NSUserDefaults standardUserDefaults] objectForKey:#"MyFavoritez"] mutableCopy]];
[self.tableView reloadData];
NSLog(#"Number of items in my array is: %d", [myFavsTwo count]);
}
and the info is coming from here:
- (void)buttonPressed:(id) sender
{
NSMutableArray *myfavs = [[[NSUserDefaults standardUserDefaults] objectForKey:#"MyFavoritez"]mutableCopy];
if(myfavs != nil)
{
NSLog(#"Array found. Contents: %#",myfavs);
}
else
{
myfavs = [[NSMutableArray alloc] initWithCapacity:0];
}
NSUserDefaults *currentDefaults = [NSUserDefaults standardUserDefaults];
NSData *dataRepresentingSavedArray = [currentDefaults objectForKey:#"MyFavoritez"];
if (dataRepresentingSavedArray != nil)
{
NSArray *oldSavedArray = [NSKeyedUnarchiver unarchiveObjectWithData:dataRepresentingSavedArray];
if (oldSavedArray != nil)
_myfavs = [[NSMutableArray alloc] initWithArray:oldSavedArray];
else
_myfavs = [[NSMutableArray alloc] init];
}
[_myfavs addObject:self.word];
[[NSUserDefaults standardUserDefaults] setObject:[NSKeyedArchiver archivedDataWithRootObject:_myfavs] forKey:#"MyFavoritez"];
[[NSUserDefaults standardUserDefaults] synchronize];
NSLog(#"Number of items in my array is: %d", [_myfavs count]);
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([[segue identifier] isEqualToString:#"passFavs"]) {
FavViewController *con = segue.destinationViewController;
con.myFavsTwo = _myfavs; }
}
hope that's not TMI
Have a look at the advice given in this answer - crash on deleteRowsAtIndexPaths in particular it is good practice to bracket your updates to the table view and your data model with [self.tableView beginUpdates] and [self.tableView endUpdates]

Deleting table row saved in NSUserDefualt iOS

In my application I am giving name to my PDF file with the help of AlertView textfield. The names are saving in Array of table list as well as NSUserDefault to access at any time. Now when I am deleting the single row of table the whole list of NSUserDefault is getting disappeared. Could you please suggest some trick over here in my code. Thanks in advance.
Updated code(viewDidLoad) with comments
- (void)viewDidLoad
{
[super viewDidLoad];
NSIndexPath * indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
//Checking previous NSUserDefault. Here I need trick to open the previous updated NSUserDefault
if([[NSUserDefaults standardUserDefaults] objectForKey:[NSString stringWithFormat:#"%#",[self.tablePdfListArray objectAtIndex:indexPath.row]]] != nil)
{
self.tablePdfListArray = [NSMutableArray arrayWithArray:[[NSUserDefaults standardUserDefaults] objectForKey:[NSString stringWithFormat:#"%#",[self.tablePdfListArray objectAtIndex:indexPath.row]]]];
}
}
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
if (buttonIndex == 0)
{
if(!self. tablePdfListArray)
{
self.tablePdfListArray = [[NSMutableArray alloc]init];
}
//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];
NSIndexPath * indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
[self.pdfListnameTable insertRowsAtIndexPaths:#[indexPath]withRowAnimation:UITableViewRowAnimationAutomatic];
//adding table Array in NSUserDefaults
NSUserDefaults *defaults=[NSUserDefaults standardUserDefaults];
[defaults setObject:self.tablePdfListArray forKey:[NSString stringWithFormat:#"%#.",[self.tablePdfListArray objectAtIndex:indexPath.row]]];
[defaults synchronize];
}
}
- (void)tableView:(UITableView *)tableView
commitEditingStyle:(UITableViewCellEditingStyle)editingStyle
forRowAtIndexPath:(NSIndexPath *)indexPath {
//Deleting single table row. The NSUserDefault should be updated here.
// NSString *appDomain = [[NSBundle mainBundle] bundleIdentifier];
// [[NSUserDefaults standardUserDefaults] removePersistentDomainForName:appDomain];
[[NSUserDefaults standardUserDefaults] removeObjectForKey:[NSString stringWithFormat:#"%#.",[self.tablePdfListArray objectAtIndex:indexPath.row]]];
[pdfListnameTable beginUpdates];
[pdfListnameTable deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
[pdfListnameTable deleteSections:indexes withRowAnimation:UITableViewRowAnimationFade];
[pdfListnameTable endUpdates];
}
}
As I understand you are removing all defaults when using
[[NSUserDefaults standardUserDefaults] removePersistentDomainForName:appDomain];
Just remove this line of code

The two nsmutablearray value is getting swap with another in ios

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

Resources