TableView not reloading when data is inserted into source from different source - ios

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]);
}

Related

I am trying to display detail list of may json response in UITableViewcell

Hi I am trying to display detail information of json data in second table view but their is some mistake in my logic so please help me my json response is in image and I am trying to to dispaly channel response in table view when user click the same cat_id then display all related channel list and image in second tableViewcell please help me..
-(void)getCategories
{
Service *srv=[[Service alloc]init];
NSString *str=#"http://streamtvbox.com/site/api/matrix/";//?country_code=91&phone=9173140993&fingerprint=2222222222";
NSString *method=#"channels";
NSMutableDictionary *dict=[[NSMutableDictionary alloc]init];
[srv postToURL:str withMethod:method andParams:dict completion:^(BOOL success, NSDictionary *responseObj)
{
NSDictionary *dict = [[NSDictionary alloc]initWithDictionary:[responseObj valueForKey:#"categories"]];
arrayChannelList=[responseObj valueForKey:#"channels"];
NSLog(#"Array : %#",channels);
for (NSDictionary *dict in arrayChannelList)
{
//NSArray *tempTitle = [[NSArray alloc]init];
arrayCat_Id = [dict objectForKey:#"cat_id"];
}
tempArray = [[NSArray alloc]init];
tempArray = [dict allKeys];
for(int i=0; i<tempArray.count; i++)
{
[arrayCategories addObject:[dict valueForKey:[tempArray objectAtIndex:i]]];
}
NSLog(#"%#",arrayCategories);
[tblView reloadData];
}];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
NSLog(#"%lu",(unsigned long)[arrayCategories count]);
return arrayCategories.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *simpleTableIdentifier = #"ChannelCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
}
cell.textLabel.text = [arrayCategories objectAtIndex:indexPath.row];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
DetailChannelsViewController *detailVC = (DetailChannelsViewController *)[self.storyboard instantiateViewControllerWithIdentifier:#"DetailView"];
detailVC.channelTitle = [arrayCategories objectAtIndex:indexPath.row];
detailVC.SubChannelName = arrayCat_Id;
NSLog(#"%#",arrayCat_Id);
[self.navigationController pushViewController:detailVC animated:YES];
}
Just initialize of your NSmutuableArray and add the value of with addobject like:-
arrayCat_Id=[[NSMutableArray alloc]init];
for(your logic){
[arrayCat_Id addobject:[dict objectForKey:#"cat_id"];
}

Adding data via person picker but, UITableView do not reload

I've created an UITableView with cells and i am trying to add a person's phone and name information into a cell via some functions. The problem is when i try to add a person's info, it is being added into my data array but, i cannot see the new info on UITableView cell. I tried to use reloadData function to reload UITableView, it was no use.
I have arrays for people's numbers and names. Also, i have a button which adds a person via ABPeoplePickerNavigationController.
addedContacts.h :
#import <UIKit/UIKit.h>
#import AddressBook;
#import AddressBookUI;
#interface addedContacts : UIViewController <UITextFieldDelegate, ABPeoplePickerNavigationControllerDelegate, UITableViewDelegate,
UITableViewDataSource>{
NSMutableArray* people;
NSMutableArray* numbers;
IBOutlet UITableView *tableview;
}
- (IBAction)addPerson:(id)sender;
#end
I use commitEditingStyle function to delete a person's information from the tableview. In addition, I keep people's information in defaults of application.
addedContacts.m :
#import "addedContacts.h"
#implementation addedContacts
-(void)viewDidLoad{
[super viewDidLoad];
}
- (IBAction)addPerson:(id)sender {
ABPeoplePickerNavigationController* picker = [[ABPeoplePickerNavigationController alloc] init];
picker.peoplePickerDelegate = self;
[self presentViewController:picker animated:YES completion:nil];
}
- (void)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker didSelectPerson:(ABRecordRef)person property:(ABPropertyID)property identifier:(ABMultiValueIdentifier)identifier {
[self dismissViewControllerAnimated:YES completion:nil];
}
-(BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker shouldContinueAfterSelectingPerson:(ABRecordRef)person{
NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
numbers = [[NSMutableArray alloc] initWithArray:[defaults objectForKey:#"numbers"]];
people = [[NSMutableArray alloc] initWithArray:[defaults objectForKey:#"people"]];
if(numbers.count == 0 && numbers.count == 0){
numbers = [[NSMutableArray alloc] init];
people = [[NSMutableArray alloc] init];
}
NSString *contactName = CFBridgingRelease(ABRecordCopyCompositeName(person));
NSString* nameField = [NSString stringWithFormat:#"%#", contactName ? contactName : #"No Name"];
ABMultiValueRef phoneRecord = ABRecordCopyValue(person, kABPersonPhoneProperty);
CFStringRef phoneNumber = ABMultiValueCopyValueAtIndex(phoneRecord, 0);
NSString* phoneField = (__bridge_transfer NSString *)phoneNumber;
CFRelease(phoneRecord);
[people addObject:nameField];
[numbers addObject:phoneField];
[defaults setObject:people forKey:#"people"];;
[defaults setObject:numbers forKey:#"numbers"];
[self dismissViewControllerAnimated:YES completion:nil];
return NO;
}
-(void)peoplePickerNavigationControllerDidCancel:(ABPeoplePickerNavigationController *)peoplePicker{
[self dismissViewControllerAnimated:YES completion:nil];
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
// Remove the row from data model
[people removeObjectAtIndex:indexPath.row];
[numbers removeObjectAtIndex:indexPath.row];
// Request table view to reload
[tableView reloadData];
}
-(NSInteger) numberOfSectionsInTableView: (UITableView*) tableView{
return 1;
}
-(NSInteger) tableView:(UITableView*) tableView numberOfRowsInSection:(NSInteger)section{
NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
numbers = [[NSMutableArray alloc] initWithArray:[defaults objectForKey:#"numbers"]];
return [numbers count];
}
-(UITableViewCell*) tableView: (UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
numbers = [[NSMutableArray alloc] initWithArray:[defaults objectForKey:#"numbers"]];
people = [[NSMutableArray alloc] initWithArray:[defaults objectForKey:#"people"]];
NSLog(#"%#",numbers);
NSLog(#"%#",people);
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"cell"];
if(cell == nil){
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"cell"];
cell.accessoryType = UITableViewCellAccessoryDetailButton;
}
NSLog(#"%ld", (long)indexPath.row);
NSLog(#"%ld", (long)people.count);
NSString* Tname = [people objectAtIndex:indexPath.row];
NSString* Tnumber = [numbers objectAtIndex:indexPath.row];
cell.textLabel.text = Tname;
cell.detailTextLabel.text = Tnumber;
return cell;
}
#end
Any suggestions?
1) this is something strange:
if(numbers.count == 0 && numbers.count == 0){
numbers = [[NSMutableArray alloc] init];
people = [[NSMutableArray alloc] init];
}
i think you mean
if(numbers.count == 0 && people.count == 0)
2) i think you mast insert reload of table after you add your new object into people and numbers arrays
[people addObject:nameField];
[numbers addObject:phoneField];
[tableView reloadData];
My hunch is that, there this a bug in the tableView:numberOfRowsInSection code. You need to return count of people or numbers. Not get the value from the user defaults. Since they don't have the newly added person and number.
-(NSInteger) tableView:(UITableView*) tableView numberOfRowsInSection:(NSInteger)section{
return [numbers count];
}

How to send value to anthor Page from table view iOS [duplicate]

This question already has answers here:
Passing data between view controllers
(45 answers)
Closed 8 years ago.
I have done for parsing data from JSON and put it show in Table view.
So I want to pass data (catID and catName )to another Page it's DetailPageController
how can I do like that? the below is my code.
Thanks in advance!
#import "ViewController.h"
#interface ViewController ()
{
NSMutableArray *myObject;
// A dictionary object
NSDictionary *dictionary;
// Define keys
NSString *catName;
NSString *catID;
}
#end
#implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
catName =#"Category Name";
catID=#"Category ID";
myObject = [[NSMutableArray alloc] init];
NSData *jsonSource = [NSData dataWithContentsOfURL:
[NSURL URLWithString:#"MY_URL"]];
id jsonObjects = [NSJSONSerialization JSONObjectWithData:
jsonSource options:NSJSONReadingMutableContainers error:nil];
for (NSDictionary *dataDict in jsonObjects) {
NSString *TheCatName = [dataDict objectForKey:#"cat_name"];
NSString *TheCatID = [dataDict objectForKey:#"cat_id"];
NSLog(#"cat_name: %#",TheCatName);
NSLog(#"cat_id: %#",TheCatID);
dictionary = [NSDictionary dictionaryWithObjectsAndKeys:
TheCatName, catName,
TheCatID, catID,
nil];
[myObject addObject:dictionary];
}
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return myObject.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *CellIdentifier = #"Item";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell=[[UITableViewCell alloc]initWithStyle:
UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
NSDictionary *tmpDict = [myObject objectAtIndex:indexPath.row];
NSMutableString *textcat;
textcat = [NSMutableString stringWithFormat:#"%#",
[tmpDict objectForKeyedSubscript:catName]];
NSMutableString *catid;
catid = [NSMutableString stringWithFormat:#"ID: %# ",
[tmpDict objectForKey:catID]];
cell.textLabel.text = textcat;
cell.detailTextLabel.text= catid;
return cell;
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
didSelectRowAtIndexPath
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSDictionary *tmpDict = [myObject objectAtIndex:indexPath.row];
NSMutableString *catID;
catID = [NSMutableString stringWithFormat:#"%#",
[tmpDict objectForKeyedSubscript:cat_id]];
NSLog(#"didSelectRowAtIndexPath");
/*UIAlertView *messageAlert = [[UIAlertView alloc]
initWithTitle:#"Row Selected" message:#"You've selected a row" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];*/
UIAlertView *messageAlert = [[UIAlertView alloc]
initWithTitle:#"Row Selected" message:catID delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
// Display the Hello World Message
[messageAlert show];
// Checked the selected row
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
cell.accessoryType = UITableViewCellAccessoryCheckmark;
[tableView deselectRowAtIndexPath:indexPath animated:YES];
}
First import DetailPageController in TableviewController Class with help of following line.
#import "DetailPageController.h"
Now implement following method in your TableViewController Class
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
DetailPageController * detailPageControllerOBJ_ = [[ImageOptionViewController alloc]initWithNibName:#“XIBName bundle:nil];
detailPageControllerOBJ_.dicSelectedData = [self.arrayData objectAtIndex:indexPath.row];
[self.navigationController pushViewController:detailPageControllerOBJ_ animated:YES];
}
And in DetailPageController.h put following code.
#property (nonatomic,strong) NSDictionary * dicSelectedData;
You will get your selected data in dicSelectedData Dictionary

Does assigning an autorelease object to a retained property increase its retain count?

I would have thought 'self.data=' would retain the autorelease NSMutableArray objects and the NSMutableDictionary objects it contains, but eventually I get EXC_BAD_ACCESS when the table's cellForRowAtIndexPath method tries to access the NSDictionaries in self.data.
#property (strong, nonatomic) NSMutableArray *data;
- (void) updateReceivedData:(NSData *) jsonData
{
NSMutableArray *fetchedData = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];
self.data = [self convertDates:fetchedData withFormat:kMySQLDateTimeFormat];
[self.tableView reloadData];
}
}
- (NSMutableArray*) convertDates:(NSMutableArray *) array withFormat:(NSString *) format
{
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:format];
NSMutableArray *newArray = [NSMutableArray arrayWithArray:array];
for (NSMutableDictionary *dict in newArray)
{
for (id key in dict.allKeys)
{
if ([[dict objectForKey:key] isKindOfClass:[NSString class]])
{
NSString *value = [dict objectForKey:key];
NSDate *date = [dateFormatter dateFromString:value];
if (date) [dict setObject:date forKey:key];
}
}
}
[dateFormatter release];
return newArray;
}
BAD_ACCESS HERE thrown here between the NSLogs.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"cell";
CustomCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
NSLog (#"Cell was nil");
cell = [[[CustomCell alloc] init] autorelease];
}
NSDictionary *dict = [[NSDictionary alloc] init];
if (_isFiltered){
dict = [self.filteredData objectAtIndex:indexPath.row];
} else {
dict = [self.data objectAtIndex:indexPath.row];
}
NSLog (#"Filling Label 1");
cell.IDLabel.text = [[dict objectForKey:#"Id"] stringValue];
NSLog (#"Filling Label 2");
cell.firstNameLabel.text = [dict objectForKey:#"firstName"];
[dict release];
return cell;
}
Turn on zombies and see if it catches the problem (EXC_BAD_ACCESS does not necessarily mean an over-released object, but it might).
What happens to the absolute value of the retain count of an object is irrelevant.
However, a strong property implies that the object is retained, yes, if you assign through the setter (i.e. self.data = ... and not _data = ...).
Why are you releasing the dict in cellForRowAtIndexPath: . Eventhough you allocate dict, you are assigning another pointer which is an object from filteredData or data. Just remove the [data release] and while declaring data assign it as nil
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"cell";
CustomCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
NSLog (#"Cell was nil");
cell = [[[CustomCell alloc] init] autorelease];
}
// **As you will be assigning the object from filteredData/data, don't allocate here**
NSDictionary *dict = nil;
if (_isFiltered){
dict = [self.filteredData objectAtIndex:indexPath.row];
} else {
dict = [self.data objectAtIndex:indexPath.row];
}
NSLog (#"Filling Label 1");
cell.IDLabel.text = [[dict objectForKey:#"Id"] stringValue];
NSLog (#"Filling Label 2");
cell.firstNameLabel.text = [dict objectForKey:#"firstName"];
// **Release not required as you didn't allocate**
//[dict release];
return cell;
}

Get user data pass to table view?

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);
}

Resources