在删除控制器(B)中的表格行时,如何更新控制器(A)中的标签?

时间:2014-06-09 17:47:50

标签: ios delegates

我有一个视图控制器(A),其标签显示某些交易的余额。在视图控制器中我有一个容器视图,它包含一个表视图控制器(B)

当我更改视图控制器(使用Tab栏)时,余额会更新,但我想这样做,以便在控制器B中删除行时,控制器A中的标签会更新。

我只是在学习目标C而且我对代表不太满意。这是与我所说的相关的代码:

ControllerB标题

#import <UIKit/UIKit.h>

@protocol KTTransactionsTableViewControllerDelegate

-(void) updateLabelWithString:(NSString*)string;

@end

@interface KTTransactionsTableViewController : UITableViewController <UITableViewDataSource, UITableViewDelegate>


@property (strong, nonatomic)NSMutableArray *transactions;
@property (weak, nonatomic) id<KTTransactionsTableViewControllerDelegate>delegate;
@end

删除控制器B中的行:

// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {

    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the managed object for the given index path
        NSManagedObjectContext *context = [KTCoreDateHelper managedObjectContext];
        [context deleteObject:(KTTransaction*)[self.transactions objectAtIndex:indexPath.row]];

        [self.transactions removeObjectAtIndex:indexPath.row];

        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];

        // Save the context.
        NSError *error;
        if (![context save:&error]) {
            NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
            abort();
        }

        //update the balance display

        KTSummaryViewController *summaryVC = [[KTSummaryViewController alloc]init];
        NSString* remainingBalance = [summaryVC calculateBalance];
        [self.delegate updateLabelWithString:remainingBalance];

    }
}

控制器A标题

#import <UIKit/UIKit.h>
#import "KTTransactionsTableViewController.h"

@interface KTSummaryViewController : UIViewController <KTTransactionsTableViewControllerDelegate>

@property (strong, nonatomic) IBOutlet UILabel *remainingBalance;

@property (strong, nonatomic) IBOutlet UIView *dateView;
@property (strong, nonatomic) IBOutlet UIView *categoryView;
@property (strong, nonatomic) IBOutlet UISegmentedControl *segmentedControl;



- (IBAction)segmentValueChanged:(UISegmentedControl *)sender;

-(NSString*)calculateBalance;


@end

控制器实现:

#import "KTSummaryViewController.h"
#import "KTCategory.h"
#import "KTCoreDateHelper.h"
#import "KTTransaction.h"

@interface KTSummaryViewController ()

@end

@implementation KTSummaryViewController

@synthesize dateView,categoryView,remainingBalance;


- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    remainingBalance.textColor = [UIColor lightGrayColor];
}

-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    [self updateLabelWithString:[self calculateBalance]];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


-(NSString*) calculateBalance
{
    //Get all the Income transactions
    NSManagedObjectContext *context = [KTCoreDateHelper managedObjectContext];

    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"KTTransaction"
                                              inManagedObjectContext:context];
    [request setEntity:entity];

    // Specify that the request should return dictionaries.
    [request setResultType:NSDictionaryResultType];


    // Create an expression for the key path.
    NSExpression *keyPathExpression = [NSExpression expressionForKeyPath:@"amount"];

    // Create an expression to represent the sum of marks
    NSExpression *maxExpression = [NSExpression expressionForFunction:@"sum:"
                                                            arguments:@[keyPathExpression]];

    NSExpressionDescription *expressionDescription = [[NSExpressionDescription alloc] init];
    [expressionDescription setName:@"amountSum"];
    [expressionDescription setExpression:maxExpression];
    [expressionDescription setExpressionResultType:NSInteger32AttributeType];

    // Set the request's properties to fetch just the property represented by the expressions.
    [request setPropertiesToFetch:[NSArray arrayWithObject:expressionDescription]];

    // Execute the fetch.
    NSError *error = nil;
    NSArray *amountResult = [context executeFetchRequest:request error:&error];

    NSLog(@"%@", amountResult);

    NSNumber *sumOfAmounts = [[amountResult objectAtIndex:0] objectForKey:@"amountSum"];

    NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc]init];
    [numberFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];

    NSString *sumCurrency = [numberFormatter stringFromNumber:sumOfAmounts];

    NSLog(@"%@",sumCurrency);


    return sumCurrency;
}

-(void)updateLabelWithString:(NSString *)string{
    remainingBalance.text = string;

}

非常感谢任何有助于理解我做错的帮助!

1 个答案:

答案 0 :(得分:1)

看起来您从未将控制器A设置为控制器B的委托。由于B位于控制器A的容器视图中,因此在实例化这些控制器时将调用prepareForSegue。您可以将控制器A设置为那里的代理(此代码在控制器A中),

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if([segue.identifier isEqualToString:@"Embed"]) {
        KTTransactionsTableViewController *tvc = segue.destinationViewController;
        tvc.delegate = self;
    }
}

如果您只有一个来自此控制器的segue,则可以省略if语句。如果您使用该子句,请确保在IB中为segue提供与此处传递的相同的标识符。