如何检查 NSArray 是否已设置
我有一个单例(StoreManager)来帮助我管理我的应用内购买,它有一个名为productArray的属性,它的设置如下:
- (void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response
{
self.productArray = response.products;
}
在我商店的视图控制器中,我有这样的代码:
-(void)setupPrices
{
if ([[StoreManager sharedStoreManager] productArray]) {
[productArray objectAtIndex:2]...
}
它工作正常while,但现在我得到 SIGABRT:索引 2 超出空数组的范围,所以显然我的 if 语句已传递为 true,即使设置该值的方法尚未被调用。我觉得这很奇怪,所以我尝试了一些代码,似乎如果我这样做,
NSArray *array;
NSLog (@"%u", array.count);
我的访问就会很差,如果我这样做,
NSArray *array;
if (array)
NSLog(@"Array is not nil");
语句就会通过。我确信我在这里遗漏了一些东西。如何检查我的数组是否已设置?
I've got a singleton (StoreManager) to help me manage my In-App Purchases, and it has a property called productArray, which is set like so:
- (void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response
{
self.productArray = response.products;
}
In my store's view controller, I have this code:
-(void)setupPrices
{
if ([[StoreManager sharedStoreManager] productArray]) {
[productArray objectAtIndex:2]...
}
It was working fine for a while, but now I get SIGABRT: index 2 beyond bounds of empty array, so clearly my if statement has passed as true, even though the method that sets the value hasn't been called yet. I thought this was weird so I tried some code and it seems if I do
NSArray *array;
NSLog (@"%u", array.count);
I get bad access and if I do
NSArray *array;
if (array)
NSLog(@"Array is not nil");
The statement passes. I'm sure I'm missing something here. How do I check if my array has been set?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这里,
array
可能是一个未初始化的垃圾值:这里,你需要使用 NSString,而不是 ac 字符串:
但是你走在正确的道路上,因为你可以测试对象是否为 nil,然后它的数数。许多人只是写类似
if (n < [array count]) ...
的内容,因为在这种情况下,[array count]
的结果将为 0 if <代码>数组是<代码>0。只需重新考虑如何初始化对象的状态(嗯,单例......)并打开编译器警告。它还有助于添加一些健全性检查断言,以验证您的单例在外部使用时是否正确构造。
Here,
array
may be an uninitialized garbage value:Here, you need to use an NSString, not a c string:
But you are along the right path, in that you can test the object for nil, then its count. Many people just write something like
if (n < [array count]) ...
because in this case, the result of[array count]
will be 0 ifarray
is0
.Just reconsider how you initialize your objects' state (meh, singletons...) and turn up the compiler warnings. It would also help to add some sanity check assertions to verify that your singleton is constructed properly when it is used externally.
count 是 NSArray 的方法,而不是属性。
在访问索引 2 处的对象之前,检查数组的计数是否至少为 3。
count is a method of NSArray, not a property.
Check if the array's count is atleast 3 before you access the object at index 2.