objective-c - 如何检查是否已设置 NSArray

标签 objective-c ios cocoa

我有一个单例 (StoreManager) 来帮助我管理应用内购买,它有一个名为 productArray 的属性,设置如下:

- (void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response
{
    self.productArray = response.products;
}

在我商店的 View Controller 中,我有这段代码:

-(void)setupPrices 
{
    if ([[StoreManager sharedStoreManager] productArray]) {
        [productArray objectAtIndex:2]...
}

有一段时间它工作正常,但现在我得到 SIGABRT:索引 2 超出空数组的边界,很明显我的 if 语句已通过为真,即使尚未调用设置值的方法。我觉得这很奇怪,所以我尝试了一些代码,似乎我这样做了

NSArray *array;
NSLog (@"%u", array.count);

我的访问权限很差,如果我这样做的话

NSArray *array;
if (array)
    NSLog(@"Array is not nil");

声明通过。我确定我在这里遗漏了一些东西。如何检查我的阵列是否已设置?

最佳答案

在这里,array可能是未初始化的垃圾值:

NSArray *array;

在这里,您需要使用 NSString,而不是 c 字符串:

NSLog ("%u", array.count);

但是你走的路是对的,因为你可以测试对象是否为 nil,然后是它的计数。许多人只是写类似 if (n < [array count]) ... 的东西因为在这种情况下,[array count] 的结果如果 array 将为 0是0 .

只需重新考虑如何初始化对象的状态(嗯,单例...)并打开编译器警告。它还有助于添加一些健全性检查断言,以验证您的单例在外部使用时是否正确构建。

关于objective-c - 如何检查是否已设置 NSArray,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7911480/

相关文章:

ios - 哪个更快? Swift 的 .filter 还是 NSPredicate?

iphone - UITableViewCell 高亮覆盖了我的 accessoryView

ios - 应用崩溃 +[NSDecimalNumber gad_negativeOne] : issue?

ios - Obj-C - 将 CLLocation 值添加到 nsdictionary?

ios - "Can' t 为源存储找到模型 "occurring during iphone "自动轻量级迁移”?

objective-c - 将 NSData 中的字节解码为整数

cocoa - NSButton 和菜单

objective-c - ios14 , 表格 View :didSelectRowAtIndexPath not called

ios - 仅在 iOS 11 中设置顶部安全区域的背景颜色

objective-c - 在 finder 同步扩展和 XPC 之间通信