首页 > 解决方案 > 为什么全局变量的地址变了

问题描述

我在person类的.h文件中声明了一个personkey,在Person的单例方法中打印personkey的地址

#import <Foundation/Foundation.h>

static const void*  personKey = &personKey;

@interface Person : NSObject

+(instancetype)sharedPerson;

@end

#import "Person.h"

@implementation Person

static Person *_person;

+ (instancetype)sharedPerson
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _person = [[self alloc] init];
        printf("personkey111 = %p\n",personKey);
    });
    return _person;
}

@end

但是当我在另一个班级打印它时,地址已经改变了。

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    Person *p = [Person sharedPerson];
    printf("personKey222 = %p,",personKey);
}

这是我的输出

personkey111 = 0x10c70c0e8
personKey222 = 0x10c70c0e0,

标签: iosobjective-c

解决方案


.h 文件中的语句static const void* personKey = &personKey;声明了一个独立的 const 指针,其内存位置作为值。导入 .h 文件时,.h 文件只是复制前面文件的内容。这意味着您有两个独立personKey的指针包含它们自己的位置。当您声明static const void* personKey = "&personKey";时,两个指针保存 string 的位置,该位置"&personKey"位于静态区域中。


推荐阅读