我可以使用 prepareForSegue 方法在两个 View Controller 之间传递数据。但是那样的话,传递的数据不能在第二个 View Controller 的 init 方法中使用。
此外,我正在使用 XLForm。因此在 init 方法中访问数据是必要的。
谁能帮我解决这个问题。
这是第一个 View Controller 的 prepareForSegue 方法:
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([[segue identifier] isEqualToString:@"SessionToWorkout"])
{
WorkoutsViewController *vc = [segue destinationViewController];
NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
UITableViewCell *selectedCell = [self.tableView cellForRowAtIndexPath:indexPath];
cellName = selectedCell.textLabel.text;
NSString *sectionTitle = [self tableView:self.tableView titleForHeaderInSection:indexPath.section];
sectionName = sectionTitle;
vc.sectionName = sectionName;
vc.cellName = cellName;
}
}
这是第二个 View Controller 的 initWithCoder 方法:
- (instancetype)initWithCoder:(NSCoder *)coder
{
self = [super initWithCoder:coder];
if (self) {
//Retrieve Workouts from DB
NSString *day_id;
day_id = [[DBHandler database] getDayIdWhere:@[@"day_name"]
whereValues:@[cellName]];
workoutsArray = [[DBHandler database] getWorkoutsForDayWhere:@[@"day_id"]
whereValues:@[day_id]];
AppLog(@"Workouts array %@", workoutsArray);
[self initializeForm];
}
return self;
}
在 initWithCoder 方法中,我需要使用 cellName 变量的值(已从先前的 View Controller 传递给此 View Controller )来调用数据库方法。
任何想法或建议如何做到这一点? 提前致谢。
最佳答案
didSet
观察器在修改变量时调用(在变量初始化时不调用)。设置cellName 时初始化数据库:
swift :
var cellName : String = "" {
didSet {
// The cell name has been set, create the database here as in any other function
}
}
objective-C :
它在 Objective-C 中非常相似,但是您没有 didSet
观察器,而是使用自定义 setter 。唯一的区别是,因为它是一个 setter,所以你必须设置你的变量
@property(nonatomic, strong) NSString * cellName;
-(void)setCellName:(NSString *)newValue
{
// First, set the new value to the variable
_cellName = newValue;
// The cell name has been set, create the database here
}
关于iOS - 从一个 View Controller 传递数据以在另一个 View Controller 的 init 方法中使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34918218/