iOS - 从一个 View Controller 传递数据以在另一个 View Controller 的 init 方法中使用

标签 ios objective-c xlform

我可以使用 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/

相关文章:

ios - 以编程方式为自定义UIViewController设置 Storyboard ID?

ios - 将 TableView 的所有数据转换为 CollectionView 快速解析

ios - 在 iOS 中为 AVCaptureDevice 的输出设置 GrayScale

ios - Objective-C 将导航栏添加到 rootview

swift - 更改 XLFORM 行的值

ios - 带有图像和文本的 XLForm 自定义行以及 Action Objective C 上的推送 Controller

ios - 编程的 UISlider 值未更改

ios - 读出 Plist 问题

ios - 解析 XML 以读取 NSMutableArray

iphone - NSDictionary 分成两个数组(对象和键),然后按对象数组(或类似的解决方案)排序