我正在使用应用内购买教程中的代码。
错误 [__NSArrayI objectAtIndex:]: message sent to deallocated instance
发生在这里:
[self purchaseMyProduct:[validProducts objectAtIndex:0]];
这里是validProducts
使用的地方。
-(void)productsRequest:(SKProductsRequest *)request
didReceiveResponse:(SKProductsResponse *)response
{
SKProduct *validProduct = nil;
int count = [response.products count];
if (count>0) {
validProducts = response.products;
validProduct = [response.products objectAtIndex:0];
if (![validProduct.productIdentifier
isEqualToString:@"facePuppetsSave"]) {
UIAlertView *tmp = [[UIAlertView alloc]
initWithTitle:@"Not Available"
message:@"No products to purchase"
delegate:self
cancelButtonTitle:nil
otherButtonTitles:@"Ok", nil];
[tmp show];
}
}
}
我看了一些类似的SO问题,说要添加dealloc
[[SKPaymentQueue defaultQueue] removeTransactionObserver:self];
productsRequest.delegate = nil;
[productsRequest cancel];
productsRequest = nil;
但没有任何改变。
以下是其他方法,如果它们是相关的。
- (void)fetchAvailableProducts {
// NSSet *productIdentifiers = [NSSet setWithObject:@"facePuppetsSave"] ,nil];
productsRequest = [[SKProductsRequest alloc] initWithProductIdentifiers:[NSSet setWithObject:@"facePuppetsSave"]];
productsRequest.delegate = self;
[productsRequest start];
}
- (BOOL)canMakePurchases
{
return [SKPaymentQueue canMakePayments];
}
- (void)purchaseMyProduct:(SKProduct*)product{
if ([self canMakePurchases]) {
SKPayment *payment = [SKPayment paymentWithProduct:product];
[[SKPaymentQueue defaultQueue] addTransactionObserver:self];
[[SKPaymentQueue defaultQueue] addPayment:payment];
}
else{
UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:
@"Purchases are disabled in your device" message:nil delegate:
self cancelButtonTitle:@"Ok" otherButtonTitles: nil];
[alertView show];
}
}
#pragma mark StoreKit Delegate
-(void)paymentQueue:(SKPaymentQueue *)queue
updatedTransactions:(NSArray *)transactions {
for (SKPaymentTransaction *transaction in transactions) {
switch (transaction.transactionState) {
case SKPaymentTransactionStatePurchasing:
NSLog(@"Purchasing");
break;
case SKPaymentTransactionStatePurchased:
if ([transaction.payment.productIdentifier
isEqualToString:@"facePuppetsSave"]) {
NSLog(@"Purchased ");
UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:
@"Purchase is completed succesfully" message:nil delegate:
self cancelButtonTitle:@"Ok" otherButtonTitles: nil];
[alertView show];
}
[[SKPaymentQueue defaultQueue] finishTransaction:transaction];
break;
case SKPaymentTransactionStateRestored:
NSLog(@"Restored ");
[[SKPaymentQueue defaultQueue] finishTransaction:transaction];
break;
case SKPaymentTransactionStateFailed:
NSLog(@"Purchase failed ");
break;
default:
break;
}
}
}