ios - 为什么全局变量的地址变了
问题描述
我在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,
解决方案
.h 文件中的语句static const void* personKey = &personKey;
声明了一个独立的 const 指针,其内存位置作为值。导入 .h 文件时,.h 文件只是复制前面文件的内容。这意味着您有两个独立personKey
的指针包含它们自己的位置。当您声明static const void* personKey = "&personKey";
时,两个指针保存 string 的位置,该位置"&personKey"
位于静态区域中。
推荐阅读
- xml - 如何使用 xmlstarlet 合并两个 xml 文件
- http - HTTP 请求解析
- python - 如何在使用opencv和python检测后只保存眼睛图像?
- python - 通过缩进折叠时处理空行
- json - 如何更新用于存储反应博客应用程序数据的 json 文件
- css - 在移动视图中失去响应性
- c# - 用于创建动态标签的 C# 代码的 XAML 标签
- javascript - 对于使用 websockets 的简单 .io 游戏应该采取哪些安全预防措施?
- javascript - 如何使用 jquery 打印 div 内容?(确保印刷内容为彩色形式。)
- kubernetes - 使用 Flannel 将节点添加到集群:“无法加入非运行容器的网络”