在 NSObject 类中设置协议并在 UIViewController 类中调用它们
Posted
技术标签:
【中文标题】在 NSObject 类中设置协议并在 UIViewController 类中调用它们【英文标题】:Set protocols in an NSObject class and call them in a UIViewController class 【发布时间】:2017-07-19 19:01:13 【问题描述】:我是 swift 新手,我只是想知道有没有办法在 NSObject 类中声明一些委托协议并在 UIViewController 类中调用它们。我试过这样做,它会引发运行时异常。我在类中的代码如下。
NSObject 类
import UIKit
import StoreKit
class InAppPurchase: NSObject, SKProductsRequestDelegate, SKPaymentTransactionObserver
var productsList = [SKProduct]()
var productToPurchase = SKProduct()
var productID = ""
let PURCHASE_ID_PREFIX = "com.aux.ApplePaySample."
public func initPayment (productID: String)
self.productID = PURCHASE_ID_PREFIX + productID
print("Initializing Purchase Product ID: \(self.productID)")
if SKPaymentQueue.canMakePayments()
let productID: NSSet = NSSet(objects: self.productID)
let request: SKProductsRequest = SKProductsRequest(productIdentifiers: productID as! Set<String>)
request.delegate = self
request.start()
else
print("In App Purchases not enabled")
func buyProduct()
let payment = SKPayment(product: productToPurchase)
SKPaymentQueue.default().add(self)
SKPaymentQueue.default().add(payment as SKPayment)
public func productsRequest(_ request: SKProductsRequest, didReceive response: SKProductsResponse)
let myProducts = response.products
for product in myProducts
print("\(product.productIdentifier) \(product.price) \(product.localizedDescription)")
productsList.append(product)
for product in productsList
let productID = product.productIdentifier
if productID == self.productID
productToPurchase = product
buyProduct()
UIViewController 类
import UIKit
import StoreKit
class InAppViewController: UIViewController
@IBOutlet var buyButton: UIButton!
// SKProductsRequestDelegate, SKPaymentTransactionObserver
let defaults = UserDefaults.standard
var product_id: NSString?
override func viewDidLoad()
super.viewDidLoad()
InAppPurchase().initPayment(productID: "101")
从技术上讲,我的 initPayment 方法应该触发代表,但它没有发生,我没有得到我在这里缺少的东西。非常感谢您的帮助。
【问题讨论】:
【参考方案1】:应该像下面这样创建一个实例
static var shared:InAppPurchase =
return InAppPurchase()
()
【讨论】:
【参考方案2】:您没有保留 InAppPurchase 对象。在调用委托之前,它可能会被释放并设置为 nil。
尝试创建一个类变量var iap: InAppPurchase
,然后在实例化您的类时分配给该变量。
iap = InAppPurchase()
iap.initPayment(productID: "101")
这应该保留您的实例并允许它接收委托方法调用。
【讨论】:
以上是关于在 NSObject 类中设置协议并在 UIViewController 类中调用它们的主要内容,如果未能解决你的问题,请参考以下文章