设置静态全局变量 oc swift

静态全局变量分swift和oc版

swift版相对比较简单

struct Example {

    static var example:String = ""

}

oc

先写设置静态变量的方法

#import


@interface staticPool : NSObject

//静态变量的set get 方法

+(void)setName:(NSString *)Name;

+(NSString *)getName;


+(void)setAge:(NSInteger)Age;

+(NSInteger)getAge;




@end


#import "staticPool.h"

//创建静态全局变量

static NSString *name = nil;

static  NSInteger age = 0;




@implementation staticPool


+(void)setName:(NSString *)Name

{

    name = Name;

}


+(NSString *)getName

{

    return name;

}


+(void)setAge:(NSInteger)Age

{

    age = Age;

}


+(NSInteger)getAge

{

    return  age;

}




@end



然后调用设置

#import "ViewController.h"

#import "PageBViewController.h"

#import "staticPool.h"


@interface ViewController ()


@end


@implementation ViewController


- (void)viewDidLoad {

    [super viewDidLoad];

    [staticPool setAge:18];

    [staticPool setName:@"Clement"];

    

    UIButton *btn = [[UIButton alloc]initWithFrame:CGRectMake(50, 100, 200, 50)];

    [btn setTitle:@"跳转到获取页面" forState:UIControlStateNormal];

    [btn setTitleColor:[UIColor orangeColor] forState:UIControlStateNormal];

    [btn addTarget:self action:@selector(click) forControlEvents:UIControlEventTouchUpInside];

    [self.view addSubview:btn];

}



-(void)click

{

    PageBViewController *page = [[PageBViewController alloc]init];

    [self presentViewController:page animated:YES completion:nil];


}


- (void)didReceiveMemoryWarning {

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}


@end



最后在另一个页面获取

#import "PageBViewController.h"

#import "staticPool.h"


@interface PageBViewController ()


@end


@implementation PageBViewController


- (void)viewDidLoad {

    [super viewDidLoad];

    // Do any additional setup after loading the view.

    self.view.backgroundColor = [UIColor whiteColor];

    

    UILabel *name = [[UILabel alloc]initWithFrame:CGRectMake(50, 100, 200, 35)];

    UILabel *age = [[UILabel alloc]initWithFrame:CGRectMake(50, 200, 200, 35)];

    name.textColor = [UIColor orangeColor];

    age.textColor = [UIColor orangeColor];

    [self.view addSubview:name];

    [self.view addSubview:age];

   NSString *theName =  [staticPool getName];

   NSInteger theAge =  [staticPool getAge];

    name.text = theName;

    age.text = [NSString stringWithFormat:@"%d",theAge];

}


- (void)didReceiveMemoryWarning {

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}


/*

#pragma mark - Navigation


// In a storyboard-based application, you will often want to do a little preparation before navigation

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {

    // Get the new view controller using [segue destinationViewController].

    // Pass the selected object to the new view controller.

}

*/


@end


大工告成


你可能感兴趣的:(功能实现)