1. 程式人生 > >Objctive-C 全局變量

Objctive-C 全局變量

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 全局變量