Okay I have three UITableViews that I need to all originate from the same viewcontroller code. I need to populate them all from the .m file of AG_ViewController.
AG_ViewController.h
#import <UIKit/UIKit.h>
#interface AG_ViewController : UIViewController <UITableViewDelegate, UITableViewDataSource>{
IBOutlet UITableView *yesterdayTableView;
IBOutlet UITableView *tomorrowTableView;
IBOutlet UITableView *tableView;
IBOutlet UILabel *todaysDate;
IBOutlet UILabel *subtractDate;
IBOutlet UILabel *addDate;
}
#end
AG_ViewController.m
#import "AG_ViewController.h"
#import "AG_Storage.h"
#import "AG_AddItemViewController.h"
#interface AG_ViewController ()
#property NSMutableArray *mainArray;
#property NSMutableArray *yesterdayArray;
#property NSMutableArray *tomorrowArray;
#property NSDate *todayDate;
#property NSDate *tomorrowsDate;
#property NSDate *yesterdaysDate;
#property int counter;
#property(weak,nonatomic)IBOutlet UIButton *yesterdayButton;
#property(weak,nonatomic)IBOutlet UIButton *tomorrowButton;
#property(weak,nonatomic)IBOutlet UIButton *backButton;
#end
#implementation AG_ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
self.mainArray = [[NSMutableArray alloc] init];
self.yesterdayArray = [[NSMutableArray alloc]init];
self.tomorrowArray = [[NSMutableArray alloc]init];
[self loadInitialData];
}
- (void)loadInitialData
{
// Do any additional setup after loading the view, typically from a nib.
//NSDate Info
NSTimeInterval secondsPerDay = 24 * 60 * 60;
NSDate *today = [[NSDate alloc]init];
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"MMMM dd, yyyy"];
self.todayDate = today;
self.tomorrowsDate = [today dateByAddingTimeInterval: secondsPerDay];
self.yesterdaysDate = [today dateByAddingTimeInterval: -secondsPerDay];
NSString *todayString = [dateFormat stringFromDate:self.todayDate];
NSString *tomorrowString = [dateFormat stringFromDate:self.tomorrowsDate];
NSString *yesterdayString = [dateFormat stringFromDate:self.yesterdaysDate];
todaysDate.text = todayString;
addDate.text = tomorrowString;
subtractDate.text = yesterdayString;
AG_Storage *theDateToday = [[AG_Storage alloc]init];
theDateToday.todaysDate = self.todayDate;
//Populate mainArray
for (int x= 0; x!=-99; x++) {
//get ready to call the NSUserDefaults
NSData *data = [[NSUserDefaults standardUserDefaults] objectForKey:[NSString stringWithFormat:#"%#%d",todayString,x]];
AG_Storage *someStorageObject = [NSKeyedUnarchiver unarchiveObjectWithData:data];
AG_Storage *storeToArray = [[AG_Storage alloc]init];
storeToArray.itemName = someStorageObject;
if (someStorageObject != nil) {
//add the data to the mainArray and update counter
[self.mainArray addObject:storeToArray];
self.counter++;
}
else if ((someStorageObject == nil) && (x==99)){
//exit when done
x=-100;
}
}
//Populate yesterdayArray
for (int x= 0; x!=-99; x++) {
//get ready to call the NSUserDefaults
NSData *data = [[NSUserDefaults standardUserDefaults] objectForKey:[NSString stringWithFormat:#"%#%d",yesterdayString,x]];
AG_Storage *someStorageObject = [NSKeyedUnarchiver unarchiveObjectWithData:data];
AG_Storage *storeToArray = [[AG_Storage alloc]init];
storeToArray.itemName = someStorageObject;
if (someStorageObject != nil) {
//add the data to the mainArray and update counter
[self.yesterdayArray addObject:storeToArray];
self.counter++;
}
else if ((someStorageObject == nil) && (x==99)){
//exit when done
x=-100;
}
}
//Populate tomorrowArray
for (int x= 0; x!=-99; x++) {
//get ready to call the NSUserDefaults
NSData *data = [[NSUserDefaults standardUserDefaults] objectForKey:[NSString stringWithFormat:#"%#%d",tomorrowString,x]];
AG_Storage *someStorageObject = [NSKeyedUnarchiver unarchiveObjectWithData:data];
AG_Storage *storeToArray = [[AG_Storage alloc]init];
storeToArray.itemName = someStorageObject;
if (someStorageObject != nil) {
//add the data to the mainArray and update counter
[self.tomorrowArray addObject:storeToArray];
self.counter++;
}
else if ((someStorageObject == nil) && (x==99)){
//exit when done
x=-100;
}
}
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
if(tableView == tomorrowTableView){
return [self.tomorrowArray count];
}
else if(tableView == yesterdayTableView)
return [self.yesterdayArray count];
else
return [self.mainArray count];
}
- (UITableViewCell *)tableView:(UITableView *)tableViewer cellForRowAtIndexPath:(NSIndexPath *)indexPath{
UITableViewCell *cell = [tableViewer dequeueReusableCellWithIdentifier:#"thisCell"];
AG_Storage *toDoItem = [self.mainArray objectAtIndex:indexPath.row];
cell.textLabel.text = toDoItem.itemName;
if (toDoItem.completed) {
cell.accessoryType = UITableViewCellAccessoryCheckmark;
}
else{
cell.accessoryType = UITableViewCellAccessoryNone;
}
return cell;
}
- (IBAction)unwindToList:(UIStoryboardSegue *)segue
{
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"MMMM dd, yyyy"];
AG_AddItemViewController *source = [segue sourceViewController];
AG_Storage *item = source.store;
NSDate *dateCreated = item.creationDate;
NSString *todayString = [dateFormat stringFromDate:self.todayDate];
NSString *dateCreatedString = [dateFormat stringFromDate:dateCreated];
NSString *tomorrowString = [dateFormat stringFromDate:self.tomorrowsDate];
NSString *yesterdayString = [dateFormat stringFromDate:self.yesterdaysDate];
//Set up file storage!
if (item != nil) {
if ([dateCreatedString isEqualToString:todayString]) {
[self.mainArray addObject:item];
[tableView reloadData];
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:item.itemName];
[[NSUserDefaults standardUserDefaults] setObject:data forKey:[NSString stringWithFormat:#"%#%d",todayString,self.counter]];
[[NSUserDefaults standardUserDefaults] synchronize];
}
else if ([dateCreatedString isEqualToString:tomorrowString]){
[self.tomorrowArray addObject:item];
[tableView reloadData];
NSLog(#"THIS WORKED TOO :D");
}
else if ([dateCreatedString isEqualToString:yesterdayString]){
[self.yesterdayArray addObject:item];
[tableView reloadData];
NSLog(#"THIS WORKED");
}
else{
}
}
self.counter++;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - Table view delegate
- (void)tableView:(UITableView *)tableViewer didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[tableViewer deselectRowAtIndexPath:indexPath animated:NO];
AG_Storage *tappedItem = [self.mainArray objectAtIndex:indexPath.row];
tappedItem.completed = !tappedItem.completed;
[tableViewer reloadRowsAtIndexPaths:#[indexPath] withRowAnimation:UITableViewRowAnimationNone];
}
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
// Return YES if you want the specified item to be editable.
return YES;
}
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableViews commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"MMMM dd, yyyy"];
NSString *todayString = [dateFormat stringFromDate:self.todayDate];
if (editingStyle == UITableViewCellEditingStyleDelete) {
//Delete from storage
for (int x = 0; x!=-99; x++) {
NSData *data = [[NSUserDefaults standardUserDefaults] objectForKey:[NSString stringWithFormat:#"%#%d",todayString,x]];
AG_Storage *someStorageObject = [NSKeyedUnarchiver unarchiveObjectWithData:data];
AG_Storage *storeToArray = [[AG_Storage alloc]init];
storeToArray.itemName = someStorageObject;
AG_Storage *toDoItem = [self.mainArray objectAtIndex:indexPath.row];
NSString *compare = toDoItem.itemName;
//If they equal then delete from NSUserDefaults
if ([compare isEqualToString:someStorageObject]) {
[[NSUserDefaults standardUserDefaults]removeObjectForKey:[NSString stringWithFormat:#"%#%d",todayString,x]];
[[NSUserDefaults standardUserDefaults]synchronize];
x=-100;
}
else
{
}
if (x>10) {
x=-100;
}
}
[self.mainArray removeObjectAtIndex:indexPath.row];
[tableViews deleteRowsAtIndexPaths:#[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
}
}
#end
I've only ever set up one table at a time, so how do I make yesterdayTableView become populated by yesterdayArray for instance?
You can keep one tableView around.
Steps for,One tableView multiple cell as per your need
1) Design seperate cell for yesterday and tomorrow nibs/storyboard
2) swap cell on click of some button tableView:cellForRowAtIndexPath via if else conditions.
or else go for viewController containment
Several ways to do so,
If you only need to display one tableView at a time you could do something like this in your tableView:cellForRowAtIndexPath: data source method:
The stupid way
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
if (kAppState_Yesterday) { // Set the controllerstate so that it knows that the arrayDatasource should be yesterday
// create and return cell corresponding to yesterdayArray.
}
}
If all your cells look the same, you could have a NSArray *dataSource and just assign it to the different arrays.
The "a bit smarter way"
if userClicksButton `display yesterday array`
self.dataSource = self.yesterdayArray
end
In this way, your tableView:cellForRowAtIndexPath: will be more consistent since if won't be full of conditionals.
If things get more complicated, I would recommend to use Controller Containment.
Related
I cannot seem to wrap my head around population of different sections in a single uitableview. Is there any way I can do it with my current setup? I am willing to change the way my arrays are set up if I need to. I have a lot of useless code in here that I am going to remove later, but basically all of it works. The issue is that all sections are being loaded with all of the data stored in the NSMutableDictionary.
- (void)viewDidLoad
{
bannerIsVisible = NO;
bannerView.hidden = YES;
[super viewDidLoad];
//NSDate Info
self.secondsPerDay = 86400;
self.todayDate = [[NSUserDefaults standardUserDefaults]objectForKey:#"todayDate"];
self.dateFormat = [[NSDateFormatter alloc] init];
[self.dateFormat setDateFormat:#"MMMM dd, yyyy"];
self.todayString = [self.dateFormat stringFromDate:self.todayDate];
//change to string and set to the string properties
todaysDate.text = self.todayString;
//initialize the arrays and the state
self.mainArray = [[NSMutableArray alloc] init];
self.subjectArray = [[NSMutableArray alloc]init];
self.mainDictionary = [[NSMutableDictionary alloc]init];
/*The UITapGestureRecognizer will make it so the program can dismiss
the keyboard at will. */
UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc]
initWithTarget:self
action:#selector(hideKeyboard)];
[self.view addGestureRecognizer:tapGesture];
if ([[NSUserDefaults standardUserDefaults] boolForKey:#"HasLaunchedOnce"])
{
// app already launched
[self.subjectArray addObjectsFromArray:[[NSUserDefaults standardUserDefaults]arrayForKey:[NSString stringWithFormat:#"%#sections",self.todayString]]];
[[NSUserDefaults standardUserDefaults]synchronize];
}
else
{
self.counter++;
// This is the first launch ever
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:#"HasLaunchedOnce"];
[[NSUserDefaults standardUserDefaults] synchronize];
AG_Storage *store = [[AG_Storage alloc] init];
store.itemName = #"Swipe to Delete";
NSString *storeString = store.itemName;
self.counter++;
NSLog(#"counter%d",self.counter);
AG_Storage *store2 = [[AG_Storage alloc] init];
store2.itemName = #"+ Button to Add";
NSString *store2String = store2.itemName;
self.counter++;
NSString *stringStuff = #"Tap this area to add notes for the day!";
[[NSUserDefaults standardUserDefaults]setObject:stringStuff forKey:[NSString stringWithFormat:#"%#textView",self.todayString]];
[[NSUserDefaults standardUserDefaults]synchronize];
[self.subjectArray addObject:#"Test"];
[[NSUserDefaults standardUserDefaults]setObject:self.subjectArray forKey:[NSString stringWithFormat:#"%#sections",self.todayString]];
[[NSUserDefaults standardUserDefaults]synchronize];
//allocates tempDic and gives it tasks and keys
NSMutableDictionary *tempDic = [[NSMutableDictionary alloc] initWithObjectsAndKeys: storeString, [NSString stringWithFormat:#"%d",0], store2String, [NSString stringWithFormat:#"%d",1], nil];
//Sets tempDic in mainDictionary with the key Test
[self.mainDictionary setObject:tempDic forKey:[NSString stringWithFormat:#"%#",[self.subjectArray objectAtIndex:0]]];
//Saves mainDictionary
[[NSUserDefaults standardUserDefaults] setObject:self.mainDictionary forKey:[NSString stringWithFormat:#"mainDictionary%#",self.todayString ]];
[[NSUserDefaults standardUserDefaults]synchronize];
}
[self loadInitialData];
}
- (void)loadInitialData
{
// Do any additional setup after loading the view, typically from a nib.
//call my custom class and store today's date.
AG_Storage *theDateToday = [[AG_Storage alloc]init];
theDateToday.todaysDate = self.todayDate;
NSLog(#"tried loadinitialdata");
NSMutableDictionary *mutDic = [[NSUserDefaults standardUserDefaults] objectForKey:[NSString stringWithFormat:#"mainDictionary%#",self.todayString ]];
NSLog(#"%#",mutDic);
//Populate mainArray
for (int x= 0; x < self.subjectArray.count; x++) {
for (int y = 0; y != -99; y++) {
NSDictionary *tempDir = [mutDic valueForKey:[NSString stringWithFormat:#"%#",[self.subjectArray objectAtIndex:x]]];
[[NSUserDefaults standardUserDefaults] synchronize];
NSLog(#"tempDir %#",tempDir);
NSString *tempString = [tempDir valueForKey:[NSString stringWithFormat:#"%d",y]];
NSLog(#"tempString %#",tempString);
if ([tempString length] != 0) {
//add the data to the mainArray and update counter
[self.mainArray addObject:tempString];
NSLog(#"added to array%#", self.mainArray);
}
else
y = -100;
}
NSLog(#"SHOULD EXIT LOOP RIGHT NOW");
}
NSLog(#"LOOP ENDED PROPERLY");
/*Populate textviews which hold the user's notes. Populates
based on the state of the program.*/
todayTextView.text = [[NSUserDefaults standardUserDefaults]stringForKey:[NSString stringWithFormat:#"%#textView",self.todayString]];
[[NSUserDefaults standardUserDefaults] synchronize];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return self.subjectArray.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return self.mainArray.count;
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
return [self.subjectArray objectAtIndex:section];
}
- (UITableViewCell *)tableView:(UITableView *)tableViewer cellForRowAtIndexPath:(NSIndexPath *)indexPath{
//populates the table based on which view is selected.
UITableViewCell *cell = [tableViewer dequeueReusableCellWithIdentifier:#"todayCell"];
NSString *toDoItem = [self.mainArray objectAtIndex:indexPath.row];
cell.textLabel.text = toDoItem;
cell.textLabel.adjustsFontSizeToFitWidth = YES;
cell.textLabel.minimumScaleFactor = 0.5;
return cell;
}
In order to reuse sections and try to preserve your code setup, I would recommend using a [NSMutableArray] of [NSMutableArray]s. Each NSMutableArray would represent a section of your table, where the index corresponds to the section
Then in tableView:numberOfRowsInSection: you grab the array from the index using the NSInteger param.
Inside (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath you access section via indexPath.section and use that on your NSMutableArray of sections to pull out your data. From there, you then have access to data only for that section to create your rows.
Example:
self.sectionArrays = [NSMutableArray new];
....
(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return [self.sectionArrays count];
}
(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
return [[self.sectionArrays objectAtIndex:section] count];
}
(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSArray *currentSectionArray = [self.sectionArrays objectAtIndex:indexPath.section];
...
NSString *toDoItem = [currentSectionArray objectAtIndex:indexPath.row];
...
configure cell
}
I cannot for the life of me figure out how to save my data with my current setup! I've tried to use NSUserDefaults, but because i'm using a custom object it doesn't work. I've been trying to figure out how to use NSKeyedArchiver but I can't figure out where to implement it.
AG_AddItemViewController.h
#import <UIKit/UIKit.h>
#import "AG_Storage.h"
#interface AG_AddItemViewController : UIViewController
#property AG_Storage *store;
#end
AG_AddItemViewController.m
#import "AG_AddItemViewController.h"
#interface AG_AddItemViewController()
#property(weak,nonatomic)IBOutlet UITextField *textField;
#property(weak,nonatomic)IBOutlet UIButton *doneButton;
#property IBOutlet UIDatePicker *datePicker;
#property NSMutableArray *defaultsArray;
#end
#implementation AG_AddItemViewController
- (void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if (sender != self.doneButton) return;
if (self.textField.text.length > 0) {
self.store =[[AG_Storage alloc] init];
self.store.itemName = self.textField.text;
self.store.completed = NO;
NSDate *dateChosen = self.datePicker.date;
self.store.creationDate = dateChosen;
NSLog(#"%#", self.store);
[self.defaultsArray addObject:self.textField.text];
}
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
self.defaultsArray = [[NSMutableArray alloc] init];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
AG_Storage
#import <Foundation/Foundation.h>
#interface AG_Storage : NSObject
#property NSString *itemName;
#property BOOL *completed;
#property NSDate *creationDate;
#property NSDate *todaysDate;
#end
AG_ViewController.h
#import <UIKit/UIKit.h>
#interface AG_ViewController : UIViewController <UITableViewDelegate, UITableViewDataSource>{
IBOutlet UITableView *tableView;
IBOutlet UILabel *todaysDate;
IBOutlet UILabel *subtractDate;
IBOutlet UILabel *addDate;
}
#end
AG_ViewController.m
#import "AG_ViewController.h"
#import "AG_Storage.h"
#import "AG_AddItemViewController.h"
#interface AG_ViewController ()
#property NSMutableArray *mainArray;
#property NSMutableArray *yesterdayArray;
#property NSMutableArray *tomorrowArray;
#property NSDate *todayDate;
#property NSDate *tomorrowsDate;
#property NSDate *yesterdaysDate;
#end
#implementation AG_ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
self.mainArray = [[NSMutableArray alloc] init];
self.yesterdayArray = [[NSMutableArray alloc]init];
self.tomorrowArray = [[NSMutableArray alloc]init];
[self loadInitialData];
}
- (void)loadInitialData
{
// Do any additional setup after loading the view, typically from a nib.
//NSDate Info
NSTimeInterval secondsPerDay = 24 * 60 * 60;
NSDate *today = [[NSDate alloc]init];
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"MMMM dd, yyyy"];
self.todayDate = today;
self.tomorrowsDate = [today dateByAddingTimeInterval: secondsPerDay];
self.yesterdaysDate = [today dateByAddingTimeInterval: -secondsPerDay];
NSString *todayString = [dateFormat stringFromDate:self.todayDate];
NSString *tomorrowString = [dateFormat stringFromDate:self.tomorrowsDate];
NSString *yesterdayString = [dateFormat stringFromDate:self.yesterdaysDate];
todaysDate.text = todayString;
addDate.text = tomorrowString;
subtractDate.text = yesterdayString;
AG_Storage *theDateToday = [[AG_Storage alloc]init];
theDateToday.todaysDate = self.todayDate;
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults arrayForKey:todayString];
NSLog(#"Tried to load...");
[defaults synchronize];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return [self.mainArray count];
}
- (UITableViewCell *)tableView:(UITableView *)tableViewer cellForRowAtIndexPath:(NSIndexPath *)indexPath{
UITableViewCell *cell = [tableViewer dequeueReusableCellWithIdentifier:#"thisCell"];
AG_Storage *toDoItem = [self.mainArray objectAtIndex:indexPath.row];
cell.textLabel.text = toDoItem.itemName;
if (toDoItem.completed) {
cell.accessoryType = UITableViewCellAccessoryCheckmark;
}
else{
cell.accessoryType = UITableViewCellAccessoryNone;
}
return cell;
}
- (IBAction)unwindToList:(UIStoryboardSegue *)segue
{
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"MMMM dd, yyyy"];
AG_AddItemViewController *source = [segue sourceViewController];
AG_Storage *item = source.store;
NSDate *dateCreated = item.creationDate;
NSString *todayString = [dateFormat stringFromDate:self.todayDate];
NSString *dateCreatedString = [dateFormat stringFromDate:dateCreated];
NSString *tomorrowString = [dateFormat stringFromDate:self.tomorrowsDate];
NSString *yesterdayString = [dateFormat stringFromDate:self.yesterdaysDate];
//Set up file storage!
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
if (item.itemName != nil) {
if ([dateCreatedString isEqualToString:todayString]) {
[self.mainArray addObject:item];
[tableView reloadData];
[defaults setObject:self.mainArray forKey:todayString];
[defaults synchronize];
NSLog(#"Saved");
}
else if ([dateCreatedString isEqualToString:tomorrowString]){
[self.tomorrowArray addObject:item];
[tableView reloadData];
NSLog(#"THIS WORKED TOO :D");
}
else if ([dateCreatedString isEqualToString:yesterdayString]){
[self.yesterdayArray addObject:item];
[tableView reloadData];
NSLog(#"THIS WORKED");
}
else{
}
}
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - Table view delegate
- (void)tableView:(UITableView *)tableViewer didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[tableViewer deselectRowAtIndexPath:indexPath animated:NO];
AG_Storage *tappedItem = [self.mainArray objectAtIndex:indexPath.row];
tappedItem.completed = !tappedItem.completed;
[tableViewer reloadRowsAtIndexPaths:#[indexPath] withRowAnimation:UITableViewRowAnimationNone];
}
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
// Return YES if you want the specified item to be editable.
return YES;
}
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableViews commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
if (editingStyle == UITableViewCellEditingStyleDelete) {
[self.mainArray removeObjectAtIndex:indexPath.row];
[tableViews deleteRowsAtIndexPaths:#[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
}
}
#end
I'd like to use NSUserDefaults because it seems simple, but if I can't thats okay. I just cannot wrap my head around this for some reason.
EDIT: This is how I tried to implement Hyperbole's ideas...
if (item.itemName != nil) {
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:item];
[[NSUserDefaults standardUserDefaults] setObject:data forKey:#"storageObjectKey"];
[[NSUserDefaults standardUserDefaults] synchronize];
if ([dateCreatedString isEqualToString:todayString]) {
[self.mainArray addObject:item];
[tableView reloadData];
NSData *data = [[NSUserDefaults standardUserDefaults] objectForKey:#"storageObjectKey"];
AG_Storage *someStorageObject = [NSKeyedUnarchiver unarchiveObjectWithData:data];
NSLog(#"%#", someStorageObject);
NSLog(#"Saved");
}
My recommendation is to have AG_Storage declare conformity to the NSSecureCoding protocol and implement the coding methods in there. After that's done, putting those AG_Storage objects into NSUserDefaults is a trivial task.
#interface AG_Storage : NSObject <NSSecureCoding>
#end
#implementation AG_Storage
+ (BOOL)supportsSecureCoding {
return YES;
}
- (void)encodeWithCoder:(NSCoder *)encoder {
[encoder encodeObject:self.itemName forKey:#"itemNameKey"];
[encoder encodeObject:#(self.completed) forKey:#"completedKey"];
[encoder encodeObject:self.creationDate forKey:#"creationDateKey"];
[encoder encodeObject:self.todaysDate forKey:#"todaysDateKey"]; // This one doesn't seem necessary to save, though I'm sure you would know better than I would.
}
- (id)initWithCoder:(NSCoder *)decoder {
if ([decoder respondsToSelector:#selector(decodeObjectOfClass:forKey:)]) // Secure coding is only available in iOS 6
{
self.itemName = [decoder decodeObjectOfClass:[NSString class] #"itemNameKey"];
self.completed = [[decoder decodeObjectOfClass:[NSNumber class] forKey:#"completedKey"] boolValue];
self.creationDate = [decoder decodeObjectOfClass:[NSDate class] forKey:#"creationDateKey"];
self.todaysDate = [decoder decodeObjectOfClass:[NSDate class] forKey:#"todaysDateKey"];
}
else
{
self.itemName = [decoder decodeObjectForKey:#"itemNameKey"];
self.completed = [[decoder decodeObjectForKey:#"completedKey"] boolValue];
self.creationDate = [decoder decodeObjectForKey:#"creationDateKey"];
self.todaysDate = [decoder decodeObjectForKey:#"todaysDateKey"];
}
#end
The next step is to break this down into an instance of NSData for storage in NSUserDefaults:
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:someAG_StorageObject];
[[NSUserDefaults standardUserDefaults] setObject:data forKey:#"storageObjectKey"];
[[NSUserDefaults standardUserDefaults] synchronize];
And to retrieve it later:
NSData *data = [[NSUserDefaults standardDefaults] objectForKey:#"storageObjectKey"];
AG_Storage *someStorageObject = [NSKeyedUnarchiver unarchiveObjectWithData:savedData];
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
I've retrieved data from 2 different shared Google Calendars, and stored the data in an array. I need to sort the data into a sectioned UITableView, sorted by date.
Heres my code:
CalendarModel.h
#import "JSONModel.h"
#import "Time.h"
#interface CalendarModel : JSONModel
#property (strong, nonatomic) NSString* title;
#property (strong, nonatomic) NSArray<Time>* time;
#end
CalendarModel.m
#import "CalendarModel.h"
#implementation CalendarModel
+(JSONKeyMapper*)keyMapper
{
return [[JSONKeyMapper alloc] initWithDictionary:#{
#"gd$when": #"time",
#"title.$t": #"title",
}];
}
#end
Time.h
#import "JSONModel.h"
#protocol Time #end
#interface Time : JSONModel
#property (strong, nonatomic) NSString* startTime;
#property (strong, nonatomic) NSString* endTime;
#end
Time.m does nothing, as it's handled by JSONModel
SportsViewController.m
#import "SportsViewController.h"
#import "JSONModelLib.h"
#import "CalendarModel.h"
#import "Time.h"
#import "JSONValueTransformer.h"
#interface SportsViewController ()
#property (strong, nonatomic) NSMutableArray *events;
#property (strong, nonatomic) NSArray *music;
- (NSDate *)dateAtBeginningOfDayForDate:(NSDate *)inputDate;
- (NSDate *)dateByAddingYears:(NSInteger)numberOfYears toDate:(NSDate *)inputDate;
#end
#implementation SportsViewController
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
//make HTTP call
NSString* searchCall = [NSString stringWithFormat:#"http://www.google.com/calendar/feeds/kao1d80fd2u5kh7268caop11o4%%40group.calendar.google.com/public/full?alt=json"];
NSString* searchCall2 = [NSString stringWithFormat:#"http://www.google.com/calendar/feeds/3qag5m8iad46mtvsnnqbtrcjjg%%40group.calendar.google.com/public/full?alt=json"];
[JSONHTTPClient getJSONFromURLWithString: searchCall
completion:^(NSDictionary *json, JSONModelError *err) {
//got JSON back
NSLog(#"Got Sports JSON from web: %#", json);
if (err) {
[[[UIAlertView alloc] initWithTitle:#"Error"
message:[err localizedDescription]
delegate:nil
cancelButtonTitle:#"Close"
otherButtonTitles: nil] show];
return;
}
//initialize the models
_events = [CalendarModel arrayOfModelsFromDictionaries:
json[#"feed"][#"entry"]
];
if (_events) NSLog(#"Loaded successfully sports models");
//show the Events
[_events addObjectsFromArray:_music];
NSLog(#"%#", _events);
[self.tableView reloadData];
}];
[JSONHTTPClient getJSONFromURLWithString: searchCall2
completion:^(NSDictionary *json2, JSONModelError *err2) {
//got JSON back
NSLog(#"Got Music JSON from web: %#", json2);
if (err2) {
[[[UIAlertView alloc] initWithTitle:#"Error"
message:[err2 localizedDescription]
delegate:nil
cancelButtonTitle:#"Close"
otherButtonTitles: nil] show];
return;
}
//initialize the models
_music = [CalendarModel arrayOfModelsFromDictionaries:
json2[#"feed"][#"entry"]
];
if (_music) NSLog(#"Loaded successfully music models");
[_events addObjectsFromArray:_music];
//show the Events
[self.tableView reloadData];
}];
//[events addObjectsFromArray:music];
[self.tableView reloadData];
}
;
-(void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - table methods
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return _events.count;
}
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
CalendarModel* event = _events[indexPath.row];
NSString *dato = [[event.time objectAtIndex:0] startTime];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = #"yyyy-MM-dd'T'HH:mm:ss.SSSzzz";
NSDate *gmtDate = [formatter dateFromString: dato];
formatter.dateFormat = #"dd-MM-yyyy HH:mm";
dato = [formatter stringFromDate:gmtDate];
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"SportCell" forIndexPath:indexPath];
cell.textLabel.text = [NSString stringWithFormat:#"%#",
event.title
];
cell.detailTextLabel.text = dato;
return cell;
}
#end
So basically all the data i need sorted resides in the _events array. I just do not get how i sort it by date into sections. The reason why startTime and endTime are NSStrings is that, that's what i am returned by the call to the shared calendar on Google
First group all your events - you'll have to take care of variable scoping (I'm using days and groupedEvents locally but you'll have to declare those as ivars/properties)
NSMutableArray *days = [NSMutableArray array];
NSMutableDictionary *groupedEvents = [NSMutableDictionary dictionary];
- (void)groupEventsIntoDays
{
for (CalendarModel *event in _events)
{
NSString *dato = [[event.time objectAtIndex:0] startTime];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = #"yyyy-MM-dd'T'HH:mm:ss.SSSzzz";
NSDate *gmtDate = [formatter dateFromString: dato];
if (![days containsObject:gmtDate])
{
[days addObject:gmtDate];
[groupedEvents setObject:[NSMutableArray arrayWithObject:event] forKey:gmtDate];
}
else
{
[((NSMutableArray*)[groupedEvents objectForKey:gmtDate]) addObject:event];
}
}
days = [[days sortedArrayUsingSelector:#selector(compare:)] mutableCopy];
}
Section headers:
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
UIView *header = [[UIView alloc] initWithFrame:CGRectMake(0,0,tableView.frame.size.width, 30)];
UILabel *headerLabel = [[UILabel alloc] initWithFrame:header.bounds];
[header addSubview:headerLabel];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = #"dd-MM-yyyy HH:mm";
NSString *dateAsString = [formatter stringFromDate:[days objectAtIndex:section]];
[headerLabel setText:dateAsString];
return header;
}
I only touched the first two lines in your cellForRow - you can modify the rest as needed for display/formatting:
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSDate *date = [days objectAtIndex:indexPath.section];
CalendarModel *event = [((NSMutableArray*)[groupedEvents objectForKey:date]) objectAtIndex:indexPath.row];
NSString *dato = [[event.time objectAtIndex:0] startTime];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = #"yyyy-MM-dd'T'HH:mm:ss.SSSzzz";
NSDate *gmtDate = [formatter dateFromString: dato];
formatter.dateFormat = #"dd-MM-yyyy HH:mm";
dato = [formatter stringFromDate:gmtDate];
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"SportCell" forIndexPath:indexPath];
cell.textLabel.text = [NSString stringWithFormat:#"%#",
event.title
];
cell.detailTextLabel.text = dato;
return cell;
}
I want developed a similar alarm application to remind user send message, and my question is I want get user field in data like numbers, message and date to table view by array.
I do this use tabbar controller,my first view is gave to user field in all data and check save button. My second view is table view to remind user.
Now I can save the data in NSMutableArray by one time only, where I save the data again, the old data with replace. Anyone know how to do this?
My code here.
Here is save button for another view.
I call FirstView
- (IBAction)SaveAll:(id)sender{
if(numText.text == nil || textView.text == nil || Selectime == nil){
NSLog(#"error becos value null");
UIAlertView *errorview = [[UIAlertView alloc]initWithTitle:#"Error Info" message:#"You nomber , message text or date no input or select.Pls fill in all. "delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[errorview show];
[errorview release];
}else{
UILocalNotification *localNotif = [[UILocalNotification alloc] init];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
if (localNotif == nil)
return;
DataClass *obj=[DataClass getInstance];
localNotif.fireDate = obj.showdate;
NSString *getdate = [obj.showdate description];
[defaults setObject:getdate forKey:#"date"];
NSLog(#"localNotif = %#", localNotif.fireDate);
localNotif.timeZone = [NSTimeZone localTimeZone];
obj.showdate = nil;
NSString *getnum =numText.text;
[defaults setObject:getnum forKey:#"keyToLookupString"];
// Notification details
// localNotif.alertBody = [eventText text];
NSString *getmessage = self.textView.text;
[defaults setObject:getmessage forKey:#"message"];
localNotif.alertBody = self.textView.text;
NSLog(#"alertBody message = %#",localNotif.alertBody);
// Set the action button
localNotif.alertAction = #"Send Now?";
localNotif.soundName = UILocalNotificationDefaultSoundName;
localNotif.applicationIconBadgeNumber = 1;
// Specify custom data for the notification
NSDictionary *infoDict = [NSDictionary dictionaryWithObject:#"someValue" forKey:#"someKey"];
localNotif.userInfo = infoDict;
// Schedule the notification
[[UIApplication sharedApplication] scheduleLocalNotification:localNotif];
[localNotif release];
numText.text = #"";
textView.text = #"";
Selectime.text = #"";
self.textView.placeholder = NSLocalizedString(#"Event Here....",);
SaveDataView *savedata = [[SaveDataView alloc]initWithNibName:#"SaveView" bundle:nil];
[savedata.tableview reloadData];
}
}
In my table view controller I call SaveDataView.
SaveDataView.h
#import <UIKit/UIKit.h>
#interface SaveDataView : UIViewController <UITableViewDataSource,UITableViewDelegate>{
IBOutlet UITableView *tableview;
NSMutableArray *MessageArray;
NSMutableArray *NomberArray;
NSMutableArray *DateArray;
}
#property (nonatomic, retain) IBOutlet UITableView *tableview;
#property (nonatomic,retain)NSMutableArray *MessageArray;
#property (nonatomic,retain)NSMutableArray *NomberArray;
#property (nonatomic,retain)NSMutableArray *DateArray;
#end
SaveDataView.m
#import "SaveDataView.h"
#import "DataClass.h"
#import "SMSAppDelegate.h"
#implementation SaveDataView
#synthesize tableview;
#synthesize MessageArray,NomberArray,DateArray;
- (void) viewWillAppear {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *messageShow =[defaults stringForKey:#"message"];
NSString *nomberShow = [defaults stringForKey:#"keyToLookupString"];
NSString *dateShow = [defaults stringForKey:#"date"];
[MessageArray addObject:messageShow];
NSLog(#"MessageArray = %#",MessageArray);
[NomberArray addObject:nomberShow];
NSLog(#"NomberArray = %#",NomberArray);
[DateArray addObject:dateShow];
NSLog(#"DateArray = %#",DateArray);
[self.tableview reloadData];
NSLog(#"checking.... ");
//[super viewWillAppear:animated];
}
// The designated initializer. Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
/*
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization.
}
return self;
}
*/
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
NSLog(#"table view viewDidLoad");
MessageArray = [[NSMutableArray alloc] init];
NomberArray = [[NSMutableArray alloc] init];
DateArray = [[NSMutableArray alloc] init];
// [MessageArray insertObject:messageShow atIndex:[MessageArray count]];
[self viewWillAppear];
[super viewDidLoad];
}
/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
// Return YES for supported orientations.
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/
- (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc. that aren't in use.
}
- (void)viewDidUnload {
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void)dealloc {
[super dealloc];
}
#pragma mark -
#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 [[[UIApplication sharedApplication] scheduledLocalNotifications] count];
NSLog(#"in nsinteger tableview");
return [self.MessageArray count];
return [self.NomberArray count];
return [self.DateArray count];
}
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSLog(#"in uitableviewcell...");
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
}
// if (cell == nil) {
// cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier] autorelease];
//}
// Configure the cell...
//NSArray *notificationArray = [[UIApplication sharedApplication] scheduledLocalNotifications];
//UILocalNotification *notif = [notificationArray objectAtIndex:indexPath.row];
// NSString *enNote = [[NSString alloc] initWithString:string];
NSString *showmessage = [MessageArray objectAtIndex:indexPath.row];
NSString *shownomber = [NomberArray objectAtIndex:indexPath.row];
NSString *showdate = [DateArray objectAtIndex:indexPath.row];
[cell.textLabel setText:showmessage];
NSLog(#"table view settext = %#",showmessage);
cell.textLabel.textColor = [UIColor blackColor];
NSString *abc = [NSString stringWithFormat:#"%# \n %#", shownomber,showdate];
//NSString *abc = [NSString stringWithFormat:#"%# \n %#", nomber,[notif.fireDate description]];
[cell.detailTextLabel setText:abc];
cell.detailTextLabel.numberOfLines = 2;
NSLog(#"table view detailTextLabel = %#,%#",shownomber,showdate);
cell.detailTextLabel.textColor = [UIColor redColor];
cell.detailTextLabel.lineBreakMode = UILineBreakModeWordWrap;
return cell;
[self.tableview reloadData];
}
#end
Replace the viewDidLoad with viewWillappear...viewDidLoad is called only once when you loaded the view so you cant able to replace the array. viewWillappear is called everytime when the view is appeared on the screen...
EDIT:afer seeing the comments.
keep the viewdidload as it is . add these codes to your application.
-(void)viewwillappear
{
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *messageShow =[defaults stringForKey:#"message"];
NSString *nomberShow = [defaults stringForKey:#"keyToLookupString"];
NSString *dateShow = [defaults stringForKey:#"date"];
[MessageArray addObject:messageShow];
NSLog(#"MessageArray = %#",MessageArray);
[NomberArray addObject:nomberShow];
NSLog(#"NomberArray = %#",NomberArray);
[DateArray addObject:dateShow];
NSLog(#"DateArray = %#",DateArray);
}