美文网首页
Object-c 根据 内存地址 获取 对象

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

作者: Yang152412 | 来源:发表于2016-04-01 18:39 被阅读937次

    引用自 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;
    

    相关文章

      网友评论

          本文标题:Object-c 根据 内存地址 获取 对象

          本文链接:https://www.haomeiwen.com/subject/rdyylttx.html