我试图通过检索每个产品标识符的 NSUserDefaults 值来查看用户是否进行了购买。我在购买产品并且设置正确时保存了价值。
调用此键时,键值对正确显示:
NSLog(@"%@", [[NSUserDefaults standardUserDefaults] dictionaryRepresentation]);
像这样:
"com.COMPANY.PRODUCTIDENTIFIER" = 1;
但是,当我尝试实际验证该特定键值时,它总是返回 null:
for (NSString * productIdentifier in _productIdentifiers) {
NSLog(@"ProductIdentifier: %@",productIdentifier);
NSLog(@"Defaults Value: %@",[[NSUserDefaults standardUserDefaults] valueForKey:productIdentifier]);
NSLog(@"Defaults Bool: %d",[[NSUserDefaults standardUserDefaults] boolForKey:productIdentifier]);
NSLog(@"Defaults Object: %@",[[NSUserDefaults standardUserDefaults] objectForKey:productIdentifier]);
BOOL productPurchased = [[NSUserDefaults standardUserDefaults] boolForKey:productIdentifier];
if (productPurchased) {
[_purchasedProductIdentifiers addObject:productIdentifier];
NSLog(@"Previously purchased: %@", productIdentifier);
} else {
NSLog(@"Not purchased: %@", productIdentifier);
}
}
结果如下:
2013-03-10 17:45:13.609 COMPANY[1140:907] ProductIdentifier: com.COMPANY.PRODUCTIDENTIFIER
2013-03-10 17:45:13.611 COMPANY[1140:907] Defaults Value: (null)
2013-03-10 17:45:13.612 COMPANY[1140:907] Defaults Bool: 0
2013-03-10 17:45:13.611 COMPANY[1140:907] Defaults Object: (null)
注意 - 上述方法都按此顺序在同一个方法中调用,因此应用程序尚未加载默认值或类似的东西不是问题,因为该值通过“dictionaryRepresentation”方法正确显示。此外,为了隐私,公司和产品标识符已被替换。真正的应用程序中没有拼写错误,所以这不是问题。
更新
好的,这很有趣。如果我使用静态字符串作为键,它会返回正确的值。但是使用'productIdentifier'(即NSString)不会,即使记录'productIdentifier'它是完全相同的字符串......任何想法???
代码:
for (NSString *productIdentifier in _productIdentifiers) {
NSLog(@"ProductIdentifier: %@",productIdentifier);
NSLog(@"Defaults Value: %@",[[NSUserDefaults standardUserDefaults] valueForKey:productIdentifier]);
NSLog(@"Defaults Bool: %d",[[NSUserDefaults standardUserDefaults] boolForKey:productIdentifier]);
NSLog(@"Defaults Object: %@",[[NSUserDefaults standardUserDefaults] objectForKey:productIdentifier]);
NSLog(@"Static Key: %d",[[NSUserDefaults standardUserDefaults] boolForKey:@"com.COMPANY.PRODUCTIDENTIFIER"]);
BOOL productPurchased = [[NSUserDefaults standardUserDefaults] boolForKey:productIdentifier];
if (productPurchased) {
[_purchasedProductIdentifiers addObject:productIdentifier];
NSLog(@"Previously purchased: %@", productIdentifier);
} else {
NSLog(@"Not purchased: %@", productIdentifier);
}
}
结果:
2013-03-10 17:45:13.609 COMPANY[1140:907] ProductIdentifier: com.COMPANY.PRODUCTIDENTIFIER
2013-03-10 17:45:13.611 COMPANY[1140:907] Defaults Value: (null)
2013-03-10 17:45:13.612 COMPANY[1140:907] Defaults Bool: 0
2013-03-10 17:45:13.611 COMPANY[1140:907] Defaults Object: (null)
2013-03-10 17:45:13.611 COMPANY[1140:907] Static Key: 1