NSInteger 返回类型方法返回 nil
我有以下 UITableView DataSource 方法:
- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
在某些项目(即部分索引标题)上,我只想返回“无”,以便表视图不会跳转到任何部分。我试图返回 nil,但我得到了“Return gets integer from point without a cast” - 警告,因为 NSInteger 显然不是一个对象,只是 32/64 位整数的 typedef。
如何实现特定部分索引标题不返回/反应?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
此处返回 nil 是一个错误,因为您返回的是整数基元,而不是对象。 (您收到强制转换警告,因为
nil
实际上是一个#define
,其计算结果为((void *)0)
,这是一个空指针,不是整数零。)与 Cocoa 交互的 Objective-C 代码的最佳选择可能是使用NSNotFound
,一个#define
用于NSIntegerMax
,它在整个 Cocoa 中使用,表示接收者中不存在给定值等。(另一种选择是使用-1
,这是更常见的在 C 代码中,什么效果最好取决于调用代码期望和可以处理的内容。)尽管
NSNotFound
是一个有符号值,但它足够大,因此您不太可能遇到范围问题。 (NSIntegerMax
大约是NSUIntegerMax
的一半,很少有人能够在 32 位环境中远程接近 2,147,483,647 个对象,更不用说两倍了。在 64 位中,忘记它吧;在你用完索引的整数之前,你就会耗尽机器中的物理 RAM。)说到这里,Cocoa 约定是使用
NSUInteger
(而不是NSInteger
)用于索引。无符号整数不能为负数,这为索引值提供了一些健全性保护;除此之外,解决意外的整数上溢/下溢变得更加容易。如果这是自定义数据源方法(看起来是这样),我强烈建议改用无符号整数。 (记住/认识到 NSInteger 和 NSUInteger 占用相同数量的字节可能会有所帮助,它们只是以不同的方式解释这些位,因此您不会“浪费”任何空间通过切换类型。)Returning
nil
is an error here since you're returning an integer primitive, not an object. (You're getting a cast warning becausenil
is actually a#define
that evaluates to((void *)0)
, which is a null pointer, not an integer zero.) The best option for Objective-C code that interfaces with Cocoa is probably to useNSNotFound
, a#define
forNSIntegerMax
which is used throughout Cocoa to signify that a given value does not exist in the receiver, etc. (Another option is to use-1
, which is more common in C code. What works best depends on what the calling code expects and can handle.)Although
NSNotFound
is a signed value, it's big enough that you're highly unlikely to run into a range issue. (NSIntegerMax
is approximately half ofNSUIntegerMax
, and very few people get remotely close to 2,147,483,647 objects — let alone twice that many — in 32-bit land. In 64-bit, forget about it; you'll run out of physical RAM in your machine long before you run out of integers for indexes.)Speaking of which, the Cocoa convention is to use
NSUInteger
(rather thanNSInteger
) for indexes. An unsigned integer cannot be negative, which offers some sanity protection on index values; among other things, it becomes easier to sort out accidental integer overflow/underflow. If this is a custom data source method (as it seems to be) I'd strongly suggest switching to using unsigned integers. (It may help to remember/realize thatNSInteger
andNSUInteger
occupy the same number of bytes, they just interpret the bits differently, so you won't "waste" any space by switching types.)