可在iOS应用中使用的变量

时间:2013-02-04 06:03:07

标签: objective-c integer

如何设置可以从iOS应用中的任何ViewController调用的integer

示例:

FirstViewController

int n;
n = 1;

SecondViewController

- (void)viewDidLoad
{
    n = 3;
}

ThirdViewController

- (void)viewDidLoad
{
n=4
}

ForthViewController

- (void)viewDidLoad
    {
int a =0;

    a=n+10;
    }

当用户输入ThirdViewController然后ForthViewController时。 int a ForthViewController将为a = 14。

2 个答案:

答案 0 :(得分:1)

尝试使用单例例如:

.h文件

#import <Foundation/Foundation.h>

@interface SelectedView : NSObject {
NSInteger number;
}
@property (nonatomic) NSInteger number;

+ (SelectedView *) instance;

@end

你的.m文件

#import "SelectedView.h"

@implementation SelectedView

@synthesize number;

static SelectedView *sharedNumber = nil;

+ (SelectedView *)instance {
    @synchronized(self) {
        if(sharedNumber == nil)
            sharedNumber = [[self alloc] init];
    }

return sharedNumber;
}

+ (id)allocWithZone:(NSZone *)zone {
    @synchronized(self) {
        if(sharedNumber == nil) {
            sharedNumber = [super allocWithZone:zone];

            return sharedNumber;
        }
    }

    return nil;
}

- (id)copyWithZone:(NSZone *)zone {
    return self;
}

- (id)retain {
    return self;
}

- (unsigned)retainCount {
    return UINT_MAX;
 }

- (id)autorelease {
    return self;
}

然后当你想实施时,只需:

#import "SelectedView.h"
SelectedView *board = [SelectedView instance];

NSInteger integer = board.number;

答案 1 :(得分:0)

你可以制作一个公共的var / propery,例如在AppDelegate中。 访问它:

[(AppDelegate *)[[UIApplication sharedApplication] delegate] setN:4];