想要从AppDelegate增加另一个类中存在的文本字段的值

时间:2014-04-04 05:06:15

标签: objective-c macos

我想增加appDelegate中另一个类中存在的文本字段的值。  textField在TestClass.h

中定义如下
@property (assign) IBOutlet UITextField *id;

每次我加载TestClass的xib时,AppDelegate类想要增加文本字段的值。创建了一个IBAction,这样当我点击按钮时,xib就会加载TextFiled值,并且会增加。

先谢谢!!

4 个答案:

答案 0 :(得分:1)

无论何时加载xib,你的文本字段都会被重新分配,你可以更好地将该值存储在NSUserDefaults中并随时进行操作

first time set the value 

if (![[NSUserDefaults standardUserDefaults] objectForKey:@"key"])
{
    [[NSUserDefaults standardUserDefaults] setObject:@"0" forKey:@"key"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

 for set  incremented value to userdefaults value

  int i = [[NSUserDefaults standardUserDefaults] objectForKey:@"key"];  ///here is my key is @"key" while get value

 [[NSUserDefaults standardUserDefaults] setObject:[NSString stringWithFormat:@"%d",i+1] forKey:@"key"]; ///here is my key is @"key" while set value

[[NSUserDefaults standardUserDefaults] synchronize];
 NSLog("%@",[[NSUserDefaults standardUserDefaults] objectForKey:@"key"]);


 set to text field



 NSLog("%@",[[NSUserDefaults standardUserDefaults] objectForKey:@"key"]); ///here is my key is @"key" while get value and log value

 self.txtTest.text = [NSString stringWithFormat:@"%d",[[[NSUserDefaults standardUserDefaults] objectForKey:@"key"] intValue]];///here is my key is @"key" while get value

答案 1 :(得分:0)

试试这个

#import "AppDelegate.h"

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    // Override point for customization after application launch.
    [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(postNotificaiton) userInfo:nil repeats:YES];
    return YES;
}

- (void)postNotificaiton{
    [[NSNotificationCenter defaultCenter] postNotificationName:@"changeValue" object:nil];
}@end

并在你的viewcontroller中

#import "ViewController.h"

@interface ViewController ()
@property (weak, nonatomic) IBOutlet UITextField *txtFld;

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeValue) name:@"changeValue" object:nil];
}

- (void)changeValue{
    [self.txtFld setText:[NSString stringWithFormat:@"%d",[self.txtFld.text integerValue] + 1]];
}


@end

希望这有助于你

答案 2 :(得分:0)

如果您只想计算从xib加载TestClass的次数,您可以覆盖awakeFromXib并在那里增加一个静态计数器。

然后将textview中的文本设置为计数器的值。

答案 3 :(得分:0)

Haven没有与Mac OSX应用程序进行交互,但为了给你一个想法,在static中创建一个TestClass变量,每当你加载XIB时,增加静态变量并在textfield中显示。您还可以使用Singleton设计模式来处理此类功能。