1

我正在为化学反应制作一个测验应用程序。该应用程序给用户一个问题,用户在两个单独的文本字段中输入反应物和产物。

我有一个数据类,其中包含所有可能的测验问题。然后,根据特定参数,数据类从可能的问题池中选择一定数量的问题,并将它们打乱成一个数组,quizQuestions.

我也有一个视图控制器,quizController. 对于每个问题,quizController都会加载一个新的实例。vc需要数据来知道要显示哪个问题,正确答案是什么等。

这是我在数据和 vc 之间进行通信的原始解决方案。

我创建了一个数据类的实例,data. 我vc1为第一个问题创建,并将其设置data为 的属性vc1,并将其标记设置为 1,以便从数据中加载第一个问题。

在用户回答第一个问题后,我创建了一个新的视图控制器,vc2在 的方法中vc1,使标签 1 比最后一个 vc 的标签多,以便加载第二个问题,并从 ' 属性传递datavc1' vc2s。

然后我重复其他问题。

但是,这不是很好的设计,我正在寻找更好的解决方案。我认为我不能使用类方法,因为data它应该包含一组随机问题。下面我有数据类的代码。

// the data class as it is now, designed for instance methods

- (id)init {
self = [super init];
if (self) {

    //Questions of the same type belong to a "ROW" (Reaction of Week)
    //individual questions
    // Items in array: (1)Question, (2)Reactants, (3)Products, (4)Elements for keyboard

    NSArray *R1Q1 = [[NSArray alloc] initWithObjects:@"Methanol is burned completely in air", @"2CH₃OH(l) + 3O₂(g)", @"2CO₂(g) + 4H₂O", @"C,H,O", nil];
    NSArray *R1Q2 = [[NSArray alloc] initWithObjects:@"Ammonia is burned in excess oxygen gas", @"4NH₃(g) + 7H₂O(l)", @"4NO₂(g) + 6H₂O(l)", @"N,H,O", nil];
    NSArray *R1Q3 = [[NSArray alloc] initWithObjects:@"Hydrogen sulfide gas is burned in excess oxygen gas", @"2H₂S(g) + 3O₂(g)", @"CO₂(g) + 2SO₂(g)", @"H,S,O", nil];

    NSArray *R2Q1 = [[NSArray alloc] initWithObjects:@"Solid potassium is added to a flask of oxygen gas", @"K(s) + O₂(g)", @"KO₂(s)", @"K,O", nil];
    NSArray *R2Q2 = [[NSArray alloc] initWithObjects:@"Sodium metal is dropped into a flask of pure water", @"2Na(s) + H₂O(l)", @"2Na⁺(aq) + 2OH⁻(aq) + H₂(g)", @"Na,H,O", nil];
    NSArray *R2Q3 = [[NSArray alloc] initWithObjects:@"A piece of lithium is heated strongly in oxygen", @"4Li(s) + O₂(g)", @"2Li₂O(s)", @"Li,O", nil];

    NSArray *R3Q1 = [[NSArray alloc] initWithObjects:@"Solutions of potassium chloride and silver nitrate are mixed", @"Ag⁺(aq) + Cl⁻(aq)", @"AgCl(s)", @"K,Cl,Ag,N,O", nil];
    NSArray *R3Q2 = [[NSArray alloc] initWithObjects:@"Solutions of iron(III) nitrate and sodium hydroxide are mixed", @"Fe³⁺(aq) + 3OH⁻(aq)", @"Fe(OH)₃(s)", @"Fe,N,O,Na,H", nil];
    NSArray *R3Q3 = [[NSArray alloc] initWithObjects:@"Solutions of nickel iodide and barium hydroxide are mixed", @"Ni²⁺(aq) + 2OH⁻(aq)", @"Ni(OH)₂(s)", @"Ni,I,Ba,OH", nil];
    // add rest

    //organize questions into groups
    row1 = [[NSArray alloc] initWithObjects:R1Q1, R1Q2, R1Q3, nil];
    row2 = [[NSArray alloc] initWithObjects:R2Q1, R2Q2, R2Q3, nil];
    row3 = [[NSArray alloc] initWithObjects:R3Q1, R3Q2, R3Q3, nil];
    //add rest

    // array containing all questions
    allRows = [[NSMutableArray alloc] initWithObjects:row1, row2, row3, nil];

    //in a real situation, needs to be given to class dynamically 
    self.maxRowNumber = 3;
    self.questionsPerRow = 2;
}

return self;
}

- (void)selectQuestions {

self.quizQuestions = [[NSMutableArray alloc] init];

for (int j = 0; j<self.maxRowNumber; j++) {
   //shuffle each row
    NSMutableArray *row = [NSMutableArray arrayWithArray:[allRows objectAtIndex:j]];
    [row shuffle];

    //add questions from each row
    for (int k = 0; k<self.questionsPerRow; k++)       
       [quizQuestions addObject:[row objectAtIndex:k]];

}

[quizQuestions shuffle];

}

查看控制器代码摘录

    # pragma mark Cell Setup
    //1st cell in tableview
    - (void) setUpEquationCell: (UITableView *) tableView  {

    equationCell = (EquationCell *) [tableView dequeueReusableCellWithIdentifier:@"equationCell"];

    if (equationCell == nil) {   
        NSArray *nib =   [[NSBundle mainBundle] loadNibNamed:@"EquationCell" owner:self options:nil];
        equationCell = (EquationCell*) [nib objectAtIndex:0];
        [equationCell.leftButton addTarget:self action:@selector(addDissociateCell) forControlEvents:UIControlEventTouchUpInside];
        [equationCell.rightButton addTarget:self action:@selector(addBalanceCell) forControlEvents:UIControlEventTouchUpInside];
    }

}

    - (void) setUpBalanceCell: (UITableView *) tableView  {
            //2nd cell in tableview

    balanceCell = (BalanceCell *) [tableView dequeueReusableCellWithIdentifier:@"balanceCell"];

    if (balanceCell == nil) {   
        NSArray *nib =   [[NSBundle mainBundle] loadNibNamed:@"BalanceCell" owner:self options:nil];
        balanceCell = (BalanceCell*) [nib objectAtIndex:0];

        // stores data from equation cell into model
        for (FormulaLabel *label in equationCell.leftView.equationOrder) 
            [leftData.equation addObject:label.text];                                                 

        for (FormulaLabel *label in equationCell.rightView.equationOrder)  
            [rightData.equation addObject:label.text];

        [leftData setUpBalancedEquation];
        [rightData setUpBalancedEquation];
        [self setUpView:balanceCell.leftView fromArray:leftData.equation toArray:leftBalanceItems];
        [self setUpView:balanceCell.rightView fromArray:rightData.equation toArray:rightBalanceItems];
        [self addBalanceTapMethodInArray:leftBalanceItems Data:leftData];
        [self addBalanceTapMethodInArray:rightBalanceItems Data:rightData];
    }

}
    - (void) setUpDissociateCell: (UITableView *) tableView  {
    dissCell = (DissociateCell *) [tableView dequeueReusableCellWithIdentifier:@"dissCell"];

    if (dissCell == nil) {   
        NSArray *nib =   [[NSBundle mainBundle] loadNibNamed:@"DissociateCell" owner:self options:nil];
        dissCell = (DissociateCell*) [nib objectAtIndex:0];

        leftData.disEquation = [[NSMutableArray alloc] init];
        rightData.disEquation = [[NSMutableArray alloc] init];

        // stores data from equation cell into model
        for (FormulaLabel *label in equationCell.leftView.equationOrder) 
            [leftData.disEquation addObject:label.text];                                                 

        for (FormulaLabel *label in equationCell.rightView.equationOrder)  
            [rightData.disEquation addObject:label.text];

        [self setUpView:dissCell.leftView fromArray:leftData.disEquation toArray:leftDisItems];
        [self setUpView:dissCell.rightView fromArray:rightData.disEquation toArray:rightDisItems];
        [self addDissTapToArray:leftDisItems fromData:leftData inView:dissCell.leftView];
        [self addDissTapToArray:rightDisItems fromData:rightData inView:dissCell.rightView];
        [dissCell.dissociateButton addTarget:self action:@selector(dissociate) forControlEvents:UIControlEventTouchUpInside];
        }
    [dissCell.rightButton addTarget:self action:@selector(addBalanceCell) forControlEvents:UIControlEventTouchUpInside];

}




    - (void)addDissociateCell {

    [cellOrder addObject:@"dissociateCell"];
    [table reloadData];
    NSIndexPath *myIndexPath = [NSIndexPath indexPathForRow:0 inSection:([cellOrder count]-1)];
    [table scrollToRowAtIndexPath:myIndexPath atScrollPosition:UITableViewScrollPositionTop animated:YES];
}


- (void) addDissTapToArray:(NSMutableArray*)viewOrder fromData:(EquationData*)data inView:(UIView*)view {

    NSString *leftOrRight;

    if (view == dissCell.leftView) 
        leftOrRight = @"left";    
    else 
        leftOrRight = @"right";

    for (int j=0; j < [viewOrder count]; j++) {


        if (j%2==0) {
            UIView *formulaView = [viewOrder objectAtIndex:j];
            //dissociate method
            FalseTarget *target = [[FalseTarget alloc] initWithVC:self leftOrRightView:leftOrRight];
            UITapGestureRecognizer* tap = [[UITapGestureRecognizer alloc] initWithTarget:target action:@selector(dissTap:)]; 
            [formulaView addGestureRecognizer:tap];

            // cancelling method
            FalseTarget *target2 = [[FalseTarget alloc] initWithVC:self Data:data ViewList:viewOrder view:view];
            UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:target2 action:@selector(dissLongTap:)];
            [formulaView addGestureRecognizer:longPress];
                  }

    }
}
- (void)addCompoundToLabel:(UIGestureRecognizer *)recognizer leftOrRight:(NSString*)leftRight{
    if( [recognizer state] == UIGestureRecognizerStateEnded ) {
        FormulaLabel* label = (FormulaLabel*)[recognizer view];  
        dissIndex = label.tag;
        dissCell.unDissociated.text = label.text;
        currentDissCellView = leftRight;
    }
}

- (void)dissociate {

    EquationData *data;
    NSMutableArray *viewOrder;
    UIView *view;

    if ([currentDissCellView isEqualToString:@"left"]) {
        data = leftData;
        viewOrder = leftDisItems;
        view = dissCell.leftView;
    }

    else {
        data = rightData;
        viewOrder = rightDisItems;
        view = dissCell.rightView;
    }

    FormulaLabel *c1 = [dissCell.leftTextField.equationOrder objectAtIndex:0];
    FormulaLabel *c2 = [dissCell.rightTextField.equationOrder objectAtIndex:0];
    [data updateDisEquationAtIndex:dissIndex withCompound1:c1.text Compound2:c2.text];

    for (UIView *view in viewOrder) 
        [view removeFromSuperview];

    [viewOrder removeAllObjects];
    [self setUpView:view fromArray:data.disEquation toArray:viewOrder];
    [self addDissTapToArray:viewOrder fromData:data inView:view];

}

- (void) cancelIons:(id)sender fromData:(EquationData *)data inView:(UIView *)view withViewList:(NSMutableArray *)viewlist {
    if( [sender state] == UIGestureRecognizerStateEnded ) {

        FormulaLabel* label = (FormulaLabel*)[sender view];  
        int index = label.tag;
        [data.disEquation removeObjectAtIndex:index];

        for (UIView *formulaView in viewlist) 
            [formulaView removeFromSuperview];

        [viewlist removeAllObjects];
        [self setUpView:view fromArray:data.disEquation toArray:viewlist];
        [self addDissTapToArray:viewlist fromData:data inView:view];


    }
}

    - (void)addBalanceCell {

    [cellOrder addObject:@"balanceCell"];
    [table reloadData];
    NSIndexPath *myIndexPath = [NSIndexPath indexPathForRow:0 inSection:([cellOrder count]-1)];
    [table scrollToRowAtIndexPath:myIndexPath atScrollPosition:UITableViewScrollPositionTop animated:YES];

    leftBalanceItems = [[NSMutableArray alloc] init];
    rightBalanceItems = [[NSMutableArray alloc] init];
}

    - (void) addBalanceTapMethodInArray:(NSMutableArray *)balanceItems Data:(EquationData *)data {

    FalseTarget *target = [[FalseTarget alloc] initWithVC:self Data:data ViewList:balanceItems view:nil];

    for (UIView *view in balanceItems) {
        UITapGestureRecognizer* tap = [[UITapGestureRecognizer alloc] initWithTarget:target action:@selector(tap:)];
        [view addGestureRecognizer:tap];
    }

}


    - (void)updateBalanceLabelofSender:(UIGestureRecognizer*)sender fromData:(EquationData *)data inArray:(NSMutableArray *)balanceItems {

    FormulaLabel* label = (FormulaLabel*)[sender view];
    int oldWidth = label.frame.size.width;
    label.text = [data updateBalancedatIndex:label.tag];
    [label sizeToFit];
    int newWidth = label.frame.size.width;
    int difference = newWidth - oldWidth;
    int labelIndex = label.tag * 2;

    for (int j = 0; j<[balanceItems count]; j++) {
        // adjusts coordinate of  all views to the right of tapped item

        if (j > labelIndex){
            UIView *item = [balanceItems objectAtIndex:j];
            item.frame = CGRectMake(item.frame.origin.x + difference, item.frame.origin.y, item.frame.size.width, item.frame.size.height);
        }
    }
}


    - (void)setUpView:(UIView *)view fromArray:(NSMutableArray *)equationData toArray:(NSMutableArray *)balanceItems {

    int labelCount = 0; //label #
    int startingPoint = 5; //x vaiue where first label starts

    for (NSString *equationText in equationData) {

        //add text
        FormulaLabel *tempLabel = [[FormulaLabel alloc] initWithFrame:CGRectMake(startingPoint, 2, 10, 22)];
        tempLabel.text = equationText;
        [tempLabel sizeToFit];
        [view addSubview:tempLabel];
        tempLabel.tag = labelCount;
        [balanceItems addObject:tempLabel];
        //set location of '+'
        startingPoint = tempLabel.frame.origin.x + tempLabel.frame.size.width + 3;

        if (labelCount != [equationData count]-1) { //not the last label

            UILabel *plus = [[[UILabel alloc] initWithFrame:CGRectMake(startingPoint, 5, 10, 10)]autorelease];
            plus.text = @"+";
            plus.font = [UIFont systemFontOfSize:13];
            [plus sizeToFit];
            [view addSubview:plus];
            startingPoint = plus.frame.origin.x + plus.frame.size.width + 3;
            [balanceItems addObject:plus];
        }

        labelCount ++;
        [tempLabel release];
    }

}
4

3 回答 3

0

我想在这里你应该使用模型结构。

1.模型:模型代表实体。在您的情况下,我可以创建两个实体 Round, Question

@interface Round: NSObject {

    NSUInteger *roundId; // 1, 2 = if it is required to check then this mi
    NSArray *questions; // Array that contains objects for Question entity
}


@interface Question:NSObject {

    NSString *questionText;
    NSString *options1Text;
    NSString *options2Text;
    NSString *options3Text;
}


@interface DataManager:NSObject {

    NSArray *rounds; // Array that contains object for Round entity
}

+(void)sharedInstance;

2. DataManger:DataManager 将管理您的实体对象。这个数据管理器将是一个 sharedInstance 类。因此,在初始化管理器时,将创建实体并插入数据。

3. ViewController:现在在视图控制器中可以直接使用sharedInstace,像这样:

[[DataManager sharedInstance] rounds]

您可以轻松获取用于创建 sharedInstance 类的代码。

现在您可以在整个应用程序中的任何位置使用此轮次。所以它会很安静很容易访问。例如,如果您需要第 1 轮第 2 题第 3 选项,则以相同的方式编写代码

第1轮

Round *r = [[[DataManager sharedInstance] rounds] objectAtIndex:0];

问题2

Question *q = [[r questions] objectAtIndex:1];

问题文本和选项 3

NSLog(@"questionText : %@  3rd Option: %@", q.questionText, q.option3Text)

享受编码:)

于 2012-06-13T18:36:17.707 回答
0

为什么不能使用带有问题属性的视图控制器类,在该类中重载属性的 setter 方法以将 UI 更新为新数据:

在 QuestionViewController.h 文件中:

@property (retain, nonatomic) Question* myQuestionData;

在 QuestionViewController.m

-(void) setMyQuestionData:(Question*)newData {
   [myQuestionData autorelease];
   myQuestionData = [newData retain];
   [self updateUIElements];
}
于 2012-06-29T17:44:02.747 回答
0

我不会那样做,因为你强迫UIViewController他们了解数据模型(同时使它成为财产)。我会做的是一个类,使用类方法(而不是对象方法)将创建数据源。您仍然必须以UIViewController某种方式保存数据,但我认为 aNSArray或 aNSDictionary就足够了:

-(void)viewDidLoad{
  [superViewDidLoad];
  myArray = [MyModel createDataSourceForTag:myTag];
} 
于 2012-06-13T06:51:04.060 回答