Данные метки стираются, когда я возвращаюсь к экрану из таблицы в iOS

Вот мой ответ JSON со значением метки.

{
        "Dry_cleaning" = 49;
        Iron = 8;
        Name = "Shirt/Tees";
        Wash = 15;
        "Wash_Iron" = 19;
        counts = 2;
        id = 1;
        total = 98;
    },
        {
        "Dry_cleaning" = 49;
        Iron = 5;
        Name = "Kurta(short)";
        Wash = 20;
        "Wash_Iron" = 19;
        counts = 2;
        id = 2;
        total = 98;
    },
        {
        "Dry_cleaning" = 50;
        Iron = 8;
        Name = "Kurta(Long)";
        Wash = 15;
        "Wash_Iron" = 20;
        counts = 0;
        id = 3;
    },
        {
        "Dry_cleaning" = 50;
        Iron = 5;
        Name = Shorts;
        Wash = 15;
        "Wash_Iron" = 19;
        counts = 0;
        id = 4;
    },
        {
        "Dry_cleaning" = 55;
        Iron = 8;
        Name = "Trousers/Pyjamas";
        Wash = 20;
        "Wash_Iron" = 30;
        counts = 0;
        id = 5;
    },
        {
        "Dry_cleaning" = 70;
        Iron = 7;
        Name = Jeans;
        Wash = 20;
        "Wash_Iron" = 29;
        counts = 0;
        id = 6;
    },
        {
        "Dry_cleaning" = 150;
        Iron = 5;
        Name = Blazer;
        Wash = 25;
        "Wash_Iron" = 19;
        counts = 0;
        id = 7;
    },
        {
        "Dry_cleaning" = 100;
        Iron = 6;
        Name = "Leather_Jacket";
        Wash = 30;
        "Wash_Iron" = 36;
        counts = 0;
        id = 8;
    },
        {
        "Dry_cleaning" = 100;
        Iron = 13;
        Name = "Lungi/Dhoti(Long)";
        Wash = 12;
        "Wash_Iron" = 15;
        counts = 0;
        id = 9;
    },

Вот мой первый скриншот:

введите здесь описание изображения

Я завершу приращение в конкретной ячейке. Когда я нажимаю кнопку размещения заказа, отображается экран общей суммы.

Второй скриншот:

введите здесь описание изображения

Третий скриншот:

Когда я возвращаюсь к экрану, значение метки шагового двигателя равно нулю. Но мне нужно редактируемое значение в конкретной ячейке.

введите здесь описание изображения

Вот мой код.

порядок.ч

#import <UIKit/UIKit.h>
#import "customcell.h"
@interface order : UIViewController<UITableViewDataSource,UITableViewDelegate,UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet UITableView *tableview;


- (IBAction)placeorder:(id)sender;

@property (weak, nonatomic) IBOutlet UIButton *btn_placeorder;

@end

заказ.м

//
//  order.m
//  laundryapp
//
//  Created by Tranetech on 13/01/16.
//  Copyright (c) 2016 Tranetech. All rights reserved.
//

#import "order.h"
#import "customcell.h"
#import "totalamount.h"
#import "globalvariabe.h"

@interface order ()

@end

@implementation order

{
    NSDictionary *dic_property;
    // NSArray *dic_property;
    NSMutableDictionary *data;
}

- (void)viewDidLoad {
    [super viewDidLoad];
     [self.tableview reloadData];
    globalvariabe *global=[globalvariabe sharedInstance];
    [NSThread detachNewThreadSelector:@selector(fetchdata) toTarget:self withObject:nil];

    global.arrayCounts = [NSMutableArray array];


  //  NSLog(@"array count=%lu",(unsigned long)global.arrayCounts.count);



//    [self.tableview registerNib:[UINibnibWithNibName:@"customcell"bundle:nil] forCellReuseIdentifier:@"Cell"];
    // Do any additional setup after loading the view.
}

-(void)fetchdata
{
    NSString *login= [[NSString stringWithFormat:@"http:/men_dry.php"]stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

    NSLog(@"----%@", login);
    NSURL *url = [NSURL URLWithString:[login stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    //-- Get request and response though URL
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:url];


    [NSURLConnection sendAsynchronousRequest:request
                                       queue:[NSOperationQueue mainQueue]
                           completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
                               dispatch_async(dispatch_get_main_queue(), ^{
                                   if (data) {
                                       dic_property= [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
                                       NSLog(@"%@", dic_property);
                                       //                                       NSLog(@"counts=%d",[[dic_property objectForKey:@"Data"]count]);
                                       //                                       for (int i = 0; i<[[dic_property objectForKey:@"Data"] count]; i++) {
                                       //                                                   [self.arrayCounts insertObject:[NSString stringWithFormat:@"0"] atIndex:i];
                                       //                                               }
                                       NSArray *tempArray = dic_property[@"Data"];
                                       for (int i=0; i<tempArray.count; i++) {
                                           NSMutableDictionary *dictValues = [NSMutableDictionary dictionaryWithDictionary:tempArray[i]];
                                           [dictValues setValue:@"0" forKey:@"counts"];
                                           globalvariabe *global=[globalvariabe sharedInstance];
                                           [global.arrayCounts addObject:dictValues];
                                       }
                                       [self.tableview reloadData];
                                   }
                                   else {
                                       NSLog(@"network error, %@", [error localizedFailureReason]);
                                   }
                               });

                           }];


}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 100;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    globalvariabe *global=[globalvariabe sharedInstance];

    return global.arrayCounts.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *simpleTableIdentifier = @"SimpleTableItem";

    customcell *cell = (customcell *)[self.tableview dequeueReusableCellWithIdentifier:simpleTableIdentifier];
    if (cell == nil)
        cell = [[[NSBundle mainBundle] loadNibNamed:@"customcell" owner:self options:nil] objectAtIndex:0];

    globalvariabe *global=[globalvariabe sharedInstance];
//    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
//    NSMutableArray *test=[userDefaults objectForKey:@"finalarray"];
    cell.lbl_value.text = [NSString stringWithFormat:@"%@",global.arrayCounts[indexPath.row][@"counts"]];
    NSLog(@"strainfffdf=%@",[NSString stringWithFormat:@"%@",global.arrayCounts[indexPath.row][@"counts"]]);
    cell.lbl_title.text=[NSString stringWithFormat:@"%@",global.arrayCounts[indexPath.row][@"Name"]];

    cell.lbl_price.text=[NSString stringWithFormat:@"%@",global.arrayCounts[indexPath.row][@"Dry_cleaning"]];
    cell.txt1.text=[NSString stringWithFormat:@"%@",global.arrayCounts[indexPath.row][@"counts"]];
    [cell.stepper addTarget:self action:@selector(itemsChange:) forControlEvents:UIControlEventValueChanged];
    return cell;
    }

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{

}
- (void)itemsChange:(UIStepper*)stepper
{
    CGPoint cursorPosition = [stepper convertPoint:CGPointZero toView:self.tableview];
    NSIndexPath *indexPath = [self.tableview indexPathForRowAtPoint:cursorPosition];

    customcell *currentCell = (customcell *)[self.tableview cellForRowAtIndexPath:indexPath];

    double value = [stepper value];
    int x = [currentCell.lbl_value.text intValue];
    int price=[currentCell.lbl_price.text intValue];
    int y= x * price;

    [currentCell.lbl_value setText:[NSString stringWithFormat:@"%d", (int)value]];
    currentCell.txt1.text=[NSString stringWithFormat:@"%d", (int)value];

    globalvariabe *global=[globalvariabe sharedInstance];
    global.arrayCounts[indexPath.row][@"counts"] = [NSString stringWithFormat:@"%d",(int)value];
    global.arrayCounts[indexPath.row][@"total"] = [NSString stringWithFormat:@"%d",(int)y];

}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (IBAction)placeorder:(id)sender {
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"counts != %@",@"0"];
    globalvariabe *global=[globalvariabe sharedInstance];
     NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    global.filteredArray = [global.arrayCounts filteredArrayUsingPredicate:predicate];
    NSLog(@"button click event=%@",global.arrayCounts);



    if(global.filteredArray.count > 0)
    {

    [userDefaults setObject:global.filteredArray forKey:@"def_orderarraylist"];
        [userDefaults setObject:global.arrayCounts forKey:@"finalarray"];
    [userDefaults synchronize];
    }
  //  NSLog(@"value:%@",global.filteredArray);
    NSLog(@"default array=%@",[userDefaults objectForKey:@"finalarray"]);
    totalamount *nextpage=[self.storyboard instantiateViewControllerWithIdentifier:@"totalamountpage"];
    [self presentViewController:nextpage animated:YES completion:nil];
  }
@end

Как получить редактируемое значение метки, когда я вернусь на экран?


person Jigar    schedule 08.02.2016    source источник
comment
@jigar только значение steper пустое или есть пустое значение?   -  person Vvk    schedule 08.02.2016
comment
не указано только значение шагового двигателя   -  person Jigar    schedule 08.02.2016
comment
@jigar проблема. в порядке VC не так ли?   -  person Vvk    schedule 08.02.2016
comment
@jigar покажи мне свой класс globalvariabe   -  person Vvk    schedule 08.02.2016
comment
Давайте продолжим обсуждение в чате.   -  person Vvk    schedule 08.02.2016


Ответы (1)


Вместо вызова метода fetchdata в методе -(void)viewDidLoad вы должны вызывать этот метод в методе -(void)viewWillAppear:(BOOL)animated. И используйте [self.navigationController popViewControllerAnimated:YES], чтобы вернуться из контроллера просмотра.

person Hima    schedule 08.02.2016