簡體   English   中英

objc_getAssociatedObject()始終為零

[英]objc_getAssociatedObject() is always nil

我有一個很大的tableView,並且我想在用戶選擇一個單元格后在tableView中添加d​​atePickers。

我正在使用objc_setAssociatedObject()和objc_getAssociatedObject()而不是使用太多變量。

我的問題是:objc_getAssociatedObject()在cellForRowAtIndexPath中始終為零...

這是我的代碼中的一個示例:(假設用戶選擇了行= 0的單元格)

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    ...

    if indexPath.row == 1 {
        var keypath = "datePicker\(indexPath.section)\(indexPath.row)"
        println(objc_getAssociatedObject(self, &keypath))
        ...
    }

}

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    let ip = NSIndexPath(forRow: indexPath.row+1, inSection: indexPath.section)
    var keypath = "datePicker\(indexPath.section)\(indexPath.row+1)"

    objc_setAssociatedObject(self, &keypath, UIDatePicker.alloc(), objc_AssociationPolicy(OBJC_ASSOCIATION_RETAIN_NONATOMIC))
    insertRowsAtIndexPaths([ip], withRowAnimation: .Top)
}

您有兩個本地keyPath變量,因此它們的地址( &keypath )自然是不相同的。 正是這個地址被用作密鑰。

keyPath升級為文件級全局文件。 現在您的代碼應該可以工作了。

我認為這里沒有使用objc_set/getAssociatedObject的理由, Dictionary<String, UIDatePicker>應該objc_set/getAssociatedObject您的需要,並且肯定會減少出錯的幾率:

var datePickers: [String: UIDatePicker] = [:]

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    ...

    if indexPath.row == 1 {
        var keypath = "datePicker\(indexPath.row)"
        println(datePickers[keypath])
        ...
    }

}

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    let ip = NSIndexPath(forRow: indexPath.row+1, inSection: indexPath.section)
    var keypath = "datePicker\(indexPath.row+1)"

    datePickers[keyPath] = UIDatePicker()
    insertRowsAtIndexPaths([ip], withRowAnimation: .Top)
}

我不知道為什么它不起作用,所以我現在更改代碼以為tableView添加NSIndexPath(s)屬性,並使用它們來跟蹤可用的datePickers。

這肯定可以解決我的問題。

您的問題是關聯密鑰不一致。

這是一個示例,詳細說明了如何構造一個包裝整齊並保持一致的關聯密鑰。 在iOS和OSX上工作。 (靜態字符串常量在iOS上有效, 但在OSX無效

class MyClass : NSObject
{
    static let AssociationKey = UnsafePointer<Int>(bitPattern: 0)

    var attactedProperty: String?
    {
        get
        {
            return objc_getAssociatedObject(self, MyClass.AssociationKey) as? String
        }
        set
        {
            objc_setAssociatedObject(self, MyClass.AssociationKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        }
    }
}

由於關聯使用原始指針值; 如果在哪里使用static let AssociationKey = "fred"則將String隱式包裝到UnsafePointer<>將在傳遞給objc_getAssociatedObject時創建一個新的包裝器實例。 這個新實例將具有不同的指針值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM