iOS - 将数据从一个视图控制器传递到另一个视图控制器的init方法中使用
问题描述:
我可以使用prepareForSegue方法在两个视图控制器之间传递数据。但是通过这种方式,传递的数据不能在第二个视图控制器的init方法中使用。iOS - 将数据从一个视图控制器传递到另一个视图控制器的init方法中使用
另外,我正在使用XLForm。因此在init方法内访问数据是必要的。
任何人都可以帮助我解决这个问题。
这里的第一个视图控制器的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;
}
}
而这里的第二个视图控制器的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方法,我需要使用单元名变量的值(已从前一视图控制器传递给此视图控制器)调用数据库方法。
任何想法或建议如何做到这一点? 在此先感谢。
答
当一个变量被修改时(在变量初始化时不会被调用),将调用didSet
观察者。初始化时单元名设置数据库:
斯威夫特:
var cellName : String = "" {
didSet {
// The cell name has been set, create the database here as in any other function
}
}
的Objective-C:
它在目标C颇为相似,但你不没有didSet
观察员,而是使用自定义设置器。唯一的区别是,因为它是一个二传手,你必须设置你的变量
@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
}
答
if ([[segue identifier] isEqualToString:@"SessionToWorkout"])
{
UITableViewCell *cell = sender;
// Get reference to the destination view controller
WorkoutsViewController *vc = [segue destinationViewController];
NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
//you can get cell value in didSelectRowAtIndexPath fun
cellName = cell.textLabel.text;
NSString *sectionTitle = [self tableView:self.tableView titleForHeaderInSection:indexPath.section];
sectionName = sectionTitle;
[vc setSectionName: sectionName];
[vc setCellName: cellName];
//check it have right value
NSLog(@"Cell name %@ Section name %@", cellName ,sectionName);
//*** in viewControllerB set sectionName, cellName as @property and set it to @synthesize
}
您可以使用变量'didSet'观察员,以初始化数据库。 –
@MichaëlAzevedo对不起,我不熟悉didSet观察者。你能进一步解释吗? – Isu
我刚刚加了一个答案:) –