将值从UIViewController传递到另一个

时间:2012-11-15 14:18:48

标签: iphone objective-c xcode cocoa-touch uiviewcontroller

在关闭我的FlipsideViewController之前

我有这些值

shours
sminutes
sseconds
srecharge
change

来自宣言

int shours;
int sminutes;
int sseconds;
int srecharge;
bool change;

现在我想在这些其他变量中将这些变量传递给另一个UIViewController(MainViewController)

mhours
mminutes
mseconds
mrecharge
mchange

最简单的方法是什么?

3 个答案:

答案 0 :(得分:0)

MainViewController上创建自定义对象属性并将其设置在FlipsideViewController上,或者由于某种原因无法执行此操作:创建一个对象来保存这些值并将其放入{{1}并阅读NSUserDefaults

答案 1 :(得分:0)

我只是创建一个“Model”类来保存这些变量并将模型类从一个视图控制器传递给下一个视图控制器。一旦它在view1&中链接view2在从view1转换到view2期间,然后在从view2转换回view1时自动更新。使用@property(assign)int shours,这样就可以创建setter和getter。

使用这种方法,使用segues可以正常工作。您不需要使用NSUserDefaults或NSNotificationCenter。

答案 2 :(得分:0)

我会创建一个类来保存这些值。然后在视图控制器之间传递此对象。

这样的事情:

接口文件:

//
//  MyObject.h
//  SOObjectPassing
//
//  Created by Wilson, LJ on 11/15/12.
//  Copyright (c) 2012 Arkansas Children's Hospital. All rights reserved.
//

#import <Foundation/Foundation.h>

@interface MyObject : NSObject {
    int shours;
    int sminutes;
    int sseconds;
    int srecharge;
    bool change;
}

@property (nonatomic, assign) int shours;
@property (nonatomic, assign) int sminutes;
@property (nonatomic, assign) int sseconds;
@property (nonatomic, assign) int srecharge;
@property (nonatomic, assign) BOOL change;

-(id) initWithHours:(int)hours
            minutes:(int)minutes
            seconds:(int)seconds
           recharge:(int)recharge
             changed:(BOOL)changed;

@end

实施档案:

//
//  MyObject.m
//  SOObjectPassing
//
//  Created by Wilson, LJ on 11/15/12.
//  Copyright (c) 2012 Arkansas Children's Hospital. All rights reserved.
//

#import "MyObject.h"


@implementation MyObject
@synthesize shours = _shours;
@synthesize sminutes = _sminutes;
@synthesize sseconds = _sseconds;
@synthesize srecharge = _srecharge;
@synthesize change = _change;

-(id) initWithHours:(int)hours
            minutes:(int)minutes
            seconds:(int)seconds
           recharge:(int)recharge
             changed:(BOOL)changed {

    if ((self = [super init])) {
        _shours = hours;
        _sminutes = minutes;
        _sseconds = seconds;
        _srecharge = recharge;
        _change = changed;
    }

    return self;
}
@end

并像这样实例化你的对象:

MyObject *myObject = [[MyObject alloc] initWithHours:2
                                                 minutes:3
                                                 seconds:4
                                                recharge:1
                                                 changed:NO];

然后将整个对象传递给其他VC。

Here is a sample project illustrating this.