0

我是objective-c的新手。我正在做一个带有模态视图的应用程序,它将数据传递给他的父视图。我实现了一个协议委托,并且数据可以正常传递,但它不会在其他方法中持续存在,因为当我尝试使用传递的值做某事时,在我的委托方法之外似乎为空。我在委托方法中做了一个 NSLog 并且值在那里,但是当我想在另一个方法中使用该值时似乎错过了。我没有使用ARC。

我的主 ViewController.h:

@protocol ModalViewDelegate
- (void)didReceiveWeight:(NSString *)weight andUnit:(NSString *) unit;
@end

@interface LogWeightTableViewController : UITableViewController<ModalViewDelegate> {
NSNumber *weightPassed;
}

@property (nonatomic, retain) IBOutlet UILabel *WeightSelected;
//...

我的主 ViewController.m:

//...this method is triggered ok, and _weightPassed has the value.
- (void)didReceiveWeight:(NSString *)weight andUnit:(NSString *)unit{

NSNumberFormatter *f = [[NSNumberFormatter alloc] init];
[f setNumberStyle:NSNumberFormatterDecimalStyle];
_weightPassed = [f numberFromString:weight]; //_weightPassed have null in another methods
[f release];

NSString *value = [[[NSString stringWithString:weight] stringByAppendingString:@" "] stringByAppendingString:unit];

[WeightSelected setText:valor];
}

我的模态视图.h:

@property (nonatomic, assign) id<ModalViewDelegate> delegate;

我的模态视图.m:

- (void)viewDidLoad
{
//...
LogWeightTableViewController *logWeightTVC = [[LogWeightTableViewController alloc]init];
self.delegate = logWeightTVC;

//...when i press a button to go back to main view call the delegate method:
[delegate didReceiveWeight:valor andUnit:unidad];

回到我的 MainViewController。我想用我的 _weightPassed 做点什么:

- (IBAction)saveLogToDataBase:(id)sender {
// ... do some stuff
[row setKg: _weightPassed]; //<-- here _weightPassed is null

我想我错过了一些重要的概念或其他东西,希望有人可以帮助我

4

1 回答 1

0

正如 H2CO3 建议的那样,我已经更改了我的设计模式,现在在显示模式视图之前传递了委托。我在 prepareForSegue 方法中完成了它:

 - (void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender { 
     if ([[segue identifier] isEqualToString:@"modalSegue"]) {
        ModalView *pickerView = [segue destinationViewController]; 
        pickerView.delegate = self; 
    }
}
于 2012-07-19T16:05:37.433 回答