请求 NSMutableArray 实例的计数时出现内存错误
arrayOfBookViews = [[NSMutableArray alloc] init];
BookView *book1 = [[BookView alloc] init];
[arrayOfBookViews addObject:book1];
BookView *book2 = [[BookView alloc] init];
[arrayOfBookViews addObject:book2];
NSLog(@"%@",arrayOfBookViews);
NSLog(@"%@",arrayOfBookViews.count);
运行这段代码给我: ( "", ”” ) 这是由于倒数第二行造成的。最后一行向我抛出 exc_bad_access 内存错误。由于数组及其对象已正确分配和初始化,因此我不明白为什么询问数组的计数会给我带来内存问题。我目前在 xcode 4 的程序中使用自动引用计数。
请解释为什么代码中的最后一行会产生内存错误。谢谢。
arrayOfBookViews = [[NSMutableArray alloc] init];
BookView *book1 = [[BookView alloc] init];
[arrayOfBookViews addObject:book1];
BookView *book2 = [[BookView alloc] init];
[arrayOfBookViews addObject:book2];
NSLog(@"%@",arrayOfBookViews);
NSLog(@"%@",arrayOfBookViews.count);
Running this code gives me:
(
"",
""
)
which is due to the second last line. The last line then throws me a exc_bad_access memory error. Since the array as well as its objects are properly allocated and initialized, I don't see why asking for the count of the array should give me a memory problem. I'm currently using automatic reference counting in this program with xcode 4.
Please explain why the last line in the code produces a memory error. Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
arrayOfBookViews.count
返回一个NSUInteger
。NSUInteger
不是一个对象,它是一个原语。%@
格式说明符仅调用传递给它的对象上的description
,因此您尝试调用无效的原语方法。将日志更改为
NSLog(@"%d",arrayOfBookViews.count);
你就会得到你想要的结果。arrayOfBookViews.count
returns anNSUInteger
.NSUInteger
is not an object, its a primitive. The%@
format specifier just callsdescription
on the object passed to it, so you tried to call a method on a primitive which is invalid.Change the log to
NSLog(@"%d",arrayOfBookViews.count);
and you'll get your result you wanted.您试图打印
int
值。为此使用%d
:You trying to print
int
value. Use%d
for this:请检查 NSArray 的
-count
方法的返回类型。您会发现它是一个NSUInteger
,它是unsigned int
或unsigned long
的类型定义,这是标准 C 类型。您应该在格式说明符中使用%u
或%lu
。Please check the return type of NSArray's
-count
method. You'll find it is anNSUInteger
which is a typedef tounsigned int
orunsigned long
which is a standard C type. You should be using%u
or%lu
in the format specifier.