iPhone“计数”挫折?
好吧,我知道我一定在这里遗漏了一些明显的东西。这是示例代码(当在 viewDidLoad 块中执行时,它会默默地崩溃......没有错误输出到调试控制台)。
NSMutableArray *bs = [NSMutableArray arrayWithCapacity:10];
[bs addObject:[NSNumber numberWithInteger: 2]];
NSLog(@"%@", [bs count]);
[bs release];
我缺少什么?
哦...如果有人想知道,这段代码只是我试图弄清楚为什么我无法获得 NSMutableArray 的计数,而 NSMutableArray 在程序中的其他地方实际上很重要。
Okay, I know I must be missing something obvious here. Here's the sample code (which, when executed within a viewDidLoad block silently crashes... no error output to debug console).
NSMutableArray *bs = [NSMutableArray arrayWithCapacity:10];
[bs addObject:[NSNumber numberWithInteger: 2]];
NSLog(@"%@", [bs count]);
[bs release];
What am I missing?
Oh... and in case anyone is wondering, this code is just me trying to figure out why I can't get the count of an NSMutableArray that actually matters somewhere else in the program.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
[mutableArray count] 返回一个 NSUInteger。在你的 NSLog 中,你指定一个 %@,它需要一个 NSString。 Obj-C 不会自动将整数转换为字符串,因此您需要使用:
深入了解如何使用字符串格式。这是一个链接:
http://developer.apple.com/mac/library/documentation/Cocoa/Conceptual/Strings/Articles/formatSpecifiers.html#//apple_ref/doc/uid/TP40004265-SW1
您还发布了已经自动释放的对象。根据经验,永远不要对对象调用release/autorelease,除非您自己也对其进行了alloc/retain/copy。大多数情况下,从其他类方法获取的对象已经为您自动释放,因此您不应该再次释放。
[mutableArray count] returns a NSUInteger. In your NSLog, you specify a %@, which requires a NSString. Obj-C does not automatically cast integers into strings, so you'll need to use:
Bone up on how to use string formatting. Here's a link:
http://developer.apple.com/mac/library/documentation/Cocoa/Conceptual/Strings/Articles/formatSpecifiers.html#//apple_ref/doc/uid/TP40004265-SW1
You're also releasing an object that already autoreleased. As a rule of thumb, don't ever call release/autorelease on an object, unless you yourself have also done an alloc/retain/copy on it. The majority of the time, objects you get from other class methods have already been autoreleased for you, so you shouldn't do another release.
最后不要释放!
arrayWithCapacity:10
返回一个autorelease
d 对象,这意味着它稍后会自动释放。自己释放它意味着它的计数将变为-1
并且会发生不愉快的事情! (正如您所发现的)作为一般规则,包含单词
alloc
或copy
的方法返回的对象必须由您释放,但其他人不能释放! (当然,除非你先保留它们)Don't release it at the end!
arrayWithCapacity:10
returns anautorelease
d object, which means it will get released automatically later. Releasing it yourself means it's count will go to-1
and unhappy things will happen! (As you have discovered)As a general rule, objects returned by methods containing the words
alloc
orcopy
must be released by you, but no others! (Unless, of course, you retain them first)