Xcode 4:如何在两个不同的类中使用int?

时间:2012-04-18 18:21:34

标签: objective-c ios sdk uitabbarcontroller xcode4.2

首先对不起我的英语。

我正在创建一个应用程序来计算您在按钮内触摸的次数。应用程序被UITabBarController划分:在第一个视图(类:ViewController)中有一个按钮和一个显示“int”(int counter;)值的标签,我想设置一个最大数量,所以当你触摸按钮50次时,会出现一个alertView。我想让这个最大数字变得灵活,以便你可以通过tabBar第二个视图中的滑块进行调整。

以下是代码:

ViewController.h

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController{
    int counter;
    IBOutlet UILabel *counterLabel;
}

-(IBAction)counter:(id)sender;
-(IBAction)Reset:(id)sender;

@end

ViewController.m

#import "ViewController.h"

@implementation ViewController

-(IBAction)counter:(id)sender{
    if (counter < end)  // in spite of end, I want to put Max (declared in AjustesView.h)
    {
        counter = counter+1;
        counterLabel.text = [NSString stringWithFormat:@"%i", Jugador1];

    }else
    {
        UIAlertView *alerta = [[UIAlertView alloc] initWithTitle:@"Alerta!" message:@"Ha llegado a 100 cliks" delegate:self cancelButtonTitle:@"Aceptar" otherButtonTitles:nil, nil];
        [alerta show];
        [alerta release];
    }
}

-(IBAction)Reset:(id)sender{
    counter = 0;
    counterLabel.text = [NSString stringWithFormat:@"%i", counter];
}

AjustesView.h

    @interface AjustesView : UIViewController{
    IBOutlet UISlider *maxSlider;
    IBOutlet UILabel *maxLabel;
    int max;
}

@property (nonatomic, retain) IBOutlet UISlider *maxSlider;

-(IBAction)AdjustmentOfMaximum:(id)sender;

@end

AjustesView.m

#import "AjustesView.h"

@implementation AjustesView

@synthesize maxSlider;

-(IBAction)AdjustmentOfMaximum:(id)sender{
    max = self.maxSlider.value;
    maxLabel.text = [NSString stringWithFormat:@"%i", max];
}

IB文件是.xib而不是故事板 谢谢你的时间!

2 个答案:

答案 0 :(得分:0)

您可以做的一件事是将您的int值存储在应用程序的AppDelegate中,并将其合成为属性。无论何时想要更新或获取值,您只需要从AppDelegate获取值,如此

#include "AppDelegate.h"



..

//whenever you want to access the value or update the value
AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
appDelegate.myCounter = newvalue;

答案 1 :(得分:0)

听起来你想要一个用户定义的偏好。为此,请使用NSUserDefaults

使用以下方法设置并从NSUserDefaults获取整数。

-(void)setInt:(int)myInt{
    NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
    //To set a value
    [prefs setInteger:myInt ForKey:@"myInt"];
    [prefs syncronize];
}

-(int)getInt{
//to get a value
    return [[NSUserDefaults standardUserDefaults] integerForKey:@"myInt"];
}

This is the Apple NSUserDefaults Class Reference