尝试从NSMutableArray删除未知类型时,我不确定如何将项目分配给要删除的变量。我能够深入到该类型的字符串属性,但不确定如何删除整个对象。
现在我遇到的错误是:
使用未宣布的标识符'项目'
NSMutableArray * skProducts = response.products;
for (SKProduct * skProduct in skProducts) {
NSLog(@"Found product: %@ %@ %0.2f",
skProduct.productIdentifier,
skProduct.localizedTitle,
skProduct.price.floatValue);
if ( [skProduct.productIdentifier isEqualToString:@"com.eboticon.Eboticon.baepack1"] ) {
// do found
[skProducts removeObject: item];
} else {
// do not found
}
您的当前问题是,您从未定义item
。
您(快速)用for (SKProduct * skProduct in skProducts) {
枚举,所以您可能是指skProduct
而不是item
。
修复了您将获得新错误:不允许您在枚举它时更改数组。在迭代时查看从NSmutablearray删除的最佳方法?为此解决方案。
一种方式:基于块的枚举。
[skProducts enumerateObjectsWithOptions:NSEnumerationReverse usingBlock:^(SKProduct * skProduct, NSUInteger idx, BOOL *stop) {
if ([skProduct.productIdentifier isEqualToString:@"com.eboticon.Eboticon.baepack1"] ) {
// do found
[skProducts removeObject: skProduct];
} else {
// do not found
}
}];
另一种方式:过滤所有没有不需要产品标识符的产品。
[skProducts filterUsingPredicate:[NSPredicate predicateWithFormat:@"productIdentifier != %@", @"com.eboticon.Eboticon.baepack1"]];
另一个注:
我假设,response
是SKProductsResponse
类。它的products
属性定义为@property(nonatomic, readonly) NSArray<SKProduct *> *products;
NSMutableArray * skProducts = response.products;
因此, skProducts
确实指向nsArray,而不是nsmutablearray,因为您只是键入变量,这不会转换对象,变量指向。
您想要
之类的东西NSMutableArray *skProducts = [response.products mutableCopy];
在Objective-C中您无法突变您枚举的数组(对于语法中的...是枚举)。你会崩溃。
您要么需要通过索引向后循环穿过对象,然后删除不属于的对象,或者使用NSArray
函数filterUsingPredicate
。filterUsingPredicate
可能是更好的方法,但是我经常使用NSPredicate
足以使您从头顶给您代码。
for循环版本可能看起来像这样:
if (skProducts.count == 0)
return;
for (NSInteger index = skProducts.count - 1; index >= 0; index--) {
product = skProducts[index];
if ( [skProduct.productIdentifier isEqualToString:@"com.eboticon.Eboticon.baepack1"] ) {
//Do whatever you need to do with the object before removing it
[skProducts removeObjectAtIndex: index];
}
}