【问题标题】:Why does printf fail to print out NSObject within a run loop?为什么 printf 无法在运行循环中打印出 NSObject?
【发布时间】:2019-04-02 14:52:42
【问题描述】:

我正在做一个简单的练习来使用 Objective-C 查看堆和堆栈。

我在 main 中创建了一个 NSNumber 对象——我假设它指向堆,对吧?当我尝试在对象上运行 printf 时,我收到 EXC_BAD_ACCESS 错误。

  • NSLog 工作正常 - 据我了解,NSLog 是 printf 但已扩展。
  • 我可以在 NSString 上运行 printf

过去我曾在对象上运行 printf,但这不是问题。有什么变化还是我遗漏了一些明显的东西?

当我运行调试器并打印出对象时,我得到了结果:isa

        Printing description of lifeAnswerObject:
        (NSNumber) NSNumber = {
            NSValue = {
                NSObject = {
                    isa = <read memory from 0x966d0398ef3e399b failed (0 of 8 bytes read)>

                }
            }
        }

这是什么意思?即使 NSNumber 包含在 autoreleasepool 中,此时也不应该释放它。

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        // insert code here...
        NSLog(@"Hello, World!");

        NSNumber *lifeAnswerObject = [[NSNumber alloc] initWithInt: 42];
        NSString *helloWorld = @"Hello out there world";
        NSLog(@"%@ in the heap", lifeAnswerObject);
        // EXC_BAD_ACCESS (code=EXC_I386_GPFLT)
        printf("%s", helloWorld); // survives
        printf("%s", lifeAnswerObject);
        int lifeAnswer = 42;

        printf("%d : in the stack", lifeAnswer);
    }
    return 0;
}

【问题讨论】:

    标签: objective-c


    【解决方案1】:

    这与标记指针无关。

    您永远不能使用%s 来打印对象类型。 它幸存下来只是巧合。对象的地址恰好没有导致它崩溃的数据。

    查看字符串的printf() 的输出。太垃圾了。

    如果要使用printf(),则需要提供char* 缓冲区。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-21
      • 1970-01-01
      • 2020-01-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多