Object-c 根据 内存地址 获取 对象

引用自 stackoverflow

So this works. That being said, I would be very uncomfortable relying on this in a project of mine. If that variable gets released before you scan its address, who knows what you're going to get. In that respect, I guess that breaks the "ARC compatible" criterion because who knows when that reference will get released which makes this very dangerous. Also, type safety is totally out the window.

Method 1:

NSString *pointer = @"test";
NSString *address = [NSString stringWithFormat:@"%p",pointer];

NSString *retrievedObject;
sscanf([address cStringUsingEncoding:NSUTF8StringEncoding], "%p", &retrievedObject);

Method 2:

/// this requires a "0x" formatted hex string
ptr = [ptr hasPrefix:@"0x"] ? ptr : [@"0x" stringByAppendingString:ptr];
uintptr_t hex = strtoull(ptr.UTF8String, NULL, 0);    
id gotcha = (__bridge id)(void *)hex;
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Chapter 1 In the year 1878, I took my degree of Doctor of...
    foxgti阅读 3,895评论 0 6
  • 出差第一天!感叹现在交通真的方便一会就到广州了!听这边老板说,这个中山市的百亿老板多如牛毛!好好学! 参观工厂学习
    浦大魔王76阅读 190评论 0 0
  • “别哭了……”,这话一出,对方肯定已是泪水滂沱,劝的人,也是事后诸葛亮,束手无策。 其实,有眼泪的...
    韩倾阅读 255评论 0 0
  • 这个时代里,我们应该踏下心来把自己像一颗种子一样摁到土里去,把自己像一个植物一样栽到花盆里面,让自己的根系在现实生...
    蝶衣宝贝阅读 212评论 0 0
  • 麻哈鱼,跳龙门,来年风调雨又顺!没错,这就是《熊出没•变形记》中最重要的一句话,在故事的开头和结尾都提到过。这句话...
    四叶草的泪水阅读 2,061评论 0 4