Получить данные пользователя передать в табличное представление? - PullRequest
0 голосов
/ 31 мая 2011

Я хочу, чтобы было разработано подобное приложение для напоминания, чтобы напомнить пользователю отправить сообщение, и мой вопрос заключается в том, что я хочу получить поле пользователя в таких данных, как числа, сообщение и дату, для представления таблицы по массиву.

Я делаю это с помощью контроллера вкладок, мой первый взгляд дается в поле пользователя во всех данных и проверяю кнопку сохранения. Мое второе представление - табличное представление, чтобы напомнить пользователю.

Теперь я могу сохранить данные в NSMutableArray только один раз, где я снова сохраняю старые данные с заменой. Кто-нибудь знает, как это сделать?

Мой код здесь.

Вот кнопка сохранения для другого просмотра.

Я звоню 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];
    }

}

В моем контроллере табличного представления я вызываю 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

1 Ответ

0 голосов
/ 31 мая 2011

Замените viewDidLoad на viewWillappear ... viewDidLoad вызывается только один раз, когда вы загружаете представление, чтобы вы не могли заменить массив.viewWillappear вызывается каждый раз, когда на экране появляется представление ...

РЕДАКТИРОВАТЬ: после просмотра комментариев.сохраните viewdidload как есть.добавьте эти коды в ваше приложение.

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

    }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...