代码之家  ›  专栏  ›  技术社区  ›  codemonkey

iPhone“计数”挫折?

  •  3
  • codemonkey  · 技术社区  · 16 年前

    好吧,我知道我肯定错过了一些明显的东西。下面是示例代码(当在viewDidLoad块中执行时,它会自动崩溃。。。没有错误输出到调试控制台)。

    NSMutableArray *bs = [NSMutableArray arrayWithCapacity:10];
    [bs addObject:[NSNumber numberWithInteger: 2]];
    NSLog(@"%@", [bs count]);
    [bs release];
    

    我错过了什么?

    2 回复  |  直到 15 年前
        1
  •  8
  •   David Liu    16 年前

    [可变数组计数]返回整数。在NSLog中,指定%@,这需要NSString。Obj-C不会自动将整数转换为字符串,因此您需要使用:

    NSLog(@"%u", [bs count]); // Uses %u specifier which means unsigned int
    

    钻研如何使用字符串格式。这里有一个链接:
    http://developer.apple.com/mac/library/documentation/Cocoa/Conceptual/Strings/Articles/formatSpecifiers.html#//apple_ref/doc/uid/TP40004265-SW1

        2
  •  5
  •   Chris Cooper    16 年前

    不要在最后释放它

    arrayWithCapacity:10 返回一个 autorelease -1 不开心的事情就会发生(正如你所发现的)

    一般来说,由包含单词的方法返回的对象 alloc copy