码迷,mamicode.com
首页 > 其他好文 > 详细

Objctive-C 全局变量

时间:2017-09-11 23:00:18      阅读:185      评论:0      收藏:0      [点我收藏+]

标签:objictive-c   全局变量   

一,全局变量

1,在m文件中的所有方法,类定义和函数定义之外

例:Square.m中定义一个全局变量 , 在main.m中引用

Square.m代码如下:

//
//  Square.m
//  Square
//
//  Created by Apple on 2017/9/9.
//  Copyright  2017年 Apple. All rights reserved.
//

#import "Square.h"

int global_val = 20;//定义一个全局变量

@implementation Square : Rectangle

-(void) setSide:(int)s
{
    [ self setWidth:s addHeight:s];
}
-(int) side
{
    return self.width;
}

@end

使用外部的全局变量要使用extend关键字

main.m代码如下:

//
//  main.m
//  Square
//
//  Created by Apple on 2017/9/9.
//  Copyright  2017年 Apple. All rights reserved.
//

#import <Foundation/Foundation.h>
#import "Square.h"



int main(int argc, const char * argv[]) {
    @autoreleasepool {
        extern int global_val;//
        int s = global_val;
        NSLog(@"我得到的全局变量为 : %i" , s);
        return 0;}
}

结果如下:

技术分享

既然是全局变量,那么任何地方的修改都会在全局产生作用



进一步测试

Square.m代码:

//
//  Square.m
//  Square
//
//  Created by Apple on 2017/9/9.
//  Copyright  2017年 Apple. All rights reserved.
//

#import "Square.h"

int global_val = 20;//定义一个全局变量

@implementation Square : Rectangle

-(void) setSide:(int)s
{
    [ self setWidth:s addHeight:s];
}
-(int) side
{
    return self.width;
}
-(void) change
{
    global_val = 30;//此处改变全局变量的值
}
-(int) get_global
{
    return global_val;
}
@end

main.m

//
//  main.m
//  Square
//
//  Created by Apple on 2017/9/9.
//  Copyright  2017年 Apple. All rights reserved.
//

#import <Foundation/Foundation.h>
#import "Square.h"



int main(int argc, const char * argv[]) {
    @autoreleasepool {
        extern int global_val;//
        int s = global_val;
        NSLog(@"我得到的全局变量为 : %i" , s);
        
        Square *mySquare = [[Square alloc] init];
        [mySquare change];
        NSLog(@"Square change 后 s : %i     ;;;;;  的全局变量 : %i" , s , global_val);
        
        global_val = 100;
        NSLog(@"s = %i , Square 中的全局变量 : %i " , s , [mySquare get_global]);
        return 0;}
}

结果:

技术分享

本文出自 “Better_Power_Wisdom” 博客,请务必保留此出处http://aonaufly.blog.51cto.com/3554853/1964430

Objctive-C 全局变量

标签:objictive-c   全局变量   

原文地址:http://aonaufly.blog.51cto.com/3554853/1964430

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!