2015-07-11 7 views
0

У меня есть быстрый словарь с пользовательскими объектами, и я использую его для заполнения моего UITableview. Однако, когда я заполняю словарь, я понимаю, что он удаляет предыдущие данные, когда добавляю к нему новые данные. Соответствующие блоки кода, как показано ниже:Swift словарь удаляет предыдущие данные при добавлении новых данных

var dict = Dictionary<ListItem, [ListItem]>() 

func numberOfSectionsInTableView(tableView: UITableView) -> Int 
{ 
    return 1 
} 

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int 
{ 
    return self.dict.keys.array.count 
} 

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell 
{ 
    var cell: CategoryCell! = tableView.dequeueReusableCellWithIdentifier("categoryCell", forIndexPath: indexPath) as? CategoryCell 

    if(cell == nil) 
    { 
     cell = CategoryCell(style: UITableViewCellStyle.Default, reuseIdentifier: "categoryCell") 
    } 
    else 
    { 
     cell.ClearCurrentCellContext(cell.image, labelTitle: cell.lblCategory, labelDescription: cell.lblDescription) 
    } 

    if let ip = indexPath as NSIndexPath? 
    { 
     let key = Array(self.dict.keys)[ip.row] as ListItem 
     cell.SetCell(key, image: cell.image, labelTitle: cell.lblCategory, labelDescription: cell.lblDescription) 
    } 

    return cell 
} 

И я заполняю словарь внутри этого блока:

Alamofire.request(.POST, WSConstants.WebServiceAddress, parameters: nil) 
    .responseJSON 
{(request, response, JSON, error) in 

if let jsonResult: NSDictionary = JSON as? NSDictionary 
{ 
    if let categories = jsonResult[WSConstants.CATEGORIES] as? NSDictionary 
    { 
     if let wsStatus = categories.valueForKey(WSConstants.WS_STATUS) as? String 
     { 
      if(wsStatus == "ok") 
      { 
       var mainObj: NSDictionary! 
       var mainItem: ListItem! 
       for(var i=0; i<mainJSONArray.count; i++) 
       { 
        mainObj = mainJSONArray.objectAtIndex(i) as! NSDictionary 
        mainItem = ListItem() 
        mainItem.itemId = mainObj.valueForKey(WSConstants.ID) as! Int 
        mainItem.itemName = mainObj.valueForKey(WSConstants.TITLE) as! String 
        mainItem.itemDescription = mainObj.valueForKey(WSConstants.DESCRIPTION) as! String 
        mainItem.itemIcon = mainObj.valueForKey(WSConstants.ICON) as! String 
        mainItem.parentId = mainObj.valueForKey(WSConstants.PARENT) as! Int 
        mainItem.postCount = mainObj.valueForKey(WSConstants.POST_COUNT) as! Int 
        if let subJSONArray = mainObj.valueForKey(WSConstants.SUB) as? NSArray 
        { 
         var midCategoryList: [ListItem]! = [ListItem]() 
         var subObj: NSDictionary! 
         var subItem: ListItem! 
         for(var i=0; i<subJSONArray.count; i++) 
         { 
          subObj = subJSONArray.objectAtIndex(i) as! NSDictionary 
          subItem = ListItem() 
          subItem.itemId = subObj.valueForKey(WSConstants.ID) as! Int 
          subItem.itemName = subObj.valueForKey(WSConstants.TITLE) as! String 
          subItem.itemDescription = subObj.valueForKey(WSConstants.DESCRIPTION) as! String 
          subItem.itemIcon = subObj.valueForKey(WSConstants.ICON) as! String 
          subItem.parentId = subObj.valueForKey(WSConstants.PARENT) as! Int 
          subItem.postCount = subObj.valueForKey(WSConstants.POST_COUNT) as! Int 
          midCategoryList.append(subItem) 
          subItem = nil 
          subObj = nil 
         } 
         // The code below line fills the dictionary with key and its values 
         self.dict[mainItem] = midCategoryList 
         midCategoryList = nil 
        } 
        mainItem = nil 
        mainObj = nil 
       } 
       Utility.ReloadTableViewDataWithAnimations(self.categoryTableView) 
      } 
     } 
} 
} 

ListItem класс:

class ListItem: Serializable, Hashable, NSCoding 
{ 
    var uniqueID: Int = 0 
    override var hashValue: Int { return uniqueID.hashValue } 
    var itemId: Int 
    var itemName: String! 
    var itemIcon: String! 
    var itemDescription: String! 
    var parentId: Int! 
    var postCount: Int! 
    var content: String! 

    override init() 
    { 
     self.itemId = 0 
     self.itemName = "" 
     self.itemIcon = "" 
     self.parentId = 0 
     self.postCount = 0 
     self.content = "" 
     self.itemDescription = "" 
    } 

    init(itemId: Int, itemName: String!, itemIcon: String!, itemDescription: String!, parentId: Int!, postCount: Int, content: String!, date: String!, url: String!) 
    { 
     self.itemId = itemId 
     self.itemName = itemName 
     self.itemIcon = itemIcon 
     self.parentId = parentId 
     self.postCount = postCount 
     self.content = content 
     self.itemDescription = itemDescription 
    } 

    deinit 
    { 

    } 

    required init(coder aDecoder: NSCoder) 
    { 
     self.itemId = aDecoder.decodeIntegerForKey("itemId") as Int 
     self.itemName = aDecoder.decodeObjectForKey("itemName") as! String 
     self.itemIcon = aDecoder.decodeObjectForKey("itemIcon") as! String 
     self.itemDescription = aDecoder.decodeObjectForKey("itemDescription") as! String 
    } 

    func encodeWithCoder(aCoder: NSCoder) 
    { 
     aCoder.encodeInteger(self.itemId, forKey: "itemId") 
     aCoder.encodeObject(self.itemName, forKey: "itemName") 
     aCoder.encodeObject(self.itemIcon, forKey: "itemIcon") 
     aCoder.encodeObject(self.itemDescription, forKey: "itemDescription") 
    } 
} 

func ==(lhs: ListItem, rhs: ListItem) -> Bool 
{ 
    return lhs.uniqueID == rhs.uniqueID 
} 

Это стремительная ошибка или я делаю некоторые ошибки, чтобы заполнить его?

Спасибо за ваши ответы

Кинг считает

Решение:

Причина проблемы заключается в том, что использование == вместо === в классе ListItem. Решение Даниэля Т. является правильным ответом. Спасибо вам всем.

+0

Вы проверяли, совпадает ли ваш ключ каждый раз? –

+0

Я проверил его, каждый раз печатая все ключи и значения, и проблем не было, все ключи разные. @DharmeshKheni – saksut

+0

Является ли 'ListItem' элементом или классом? –

ответ

1

Не видя больше кода, я предполагаю, что проблема заключается в вашем операторе ListItem's ==. В приведенном ниже коде отсутствует проблема, которую вы описываете:

//: Playground - noun: a place where people can play 

class ListItem: Hashable { 

    var itemId: Int = 0 
    var itemName: String = "" 
    var itemDescription: String = "" 
    var itemIcon: String = "" 
    var parentId: Int = 0 
    var postCount: Int = 0 

    var hashValue: Int { 
     return itemId.hashValue 
    } 

} 

func ==(lhs: ListItem, rhs: ListItem) -> Bool { 
    return lhs === rhs // simple identity 
} 

var dict = Dictionary<ListItem, [ListItem]>() 

let arr = [ListItem(), ListItem()] 

dict[ListItem()] = arr 
dict[ListItem()] = arr 

dict.keys.array.count 
+0

Я прав. На основе нового кода, который вы опубликовали, ваш оператор '==' сравнивает 'ListItem.uniqueID', но все они установлены в '0' и никогда не меняются. –

+0

'===' оператор действительно вызывает эту проблему? @DanielT. – saksut

+0

Снова посмотрим на ваш метод 'func =='. Все ваши объекты имеют уникальный идентификатор 0, поэтому все они идентичны в соответствии с '==' –

Смежные вопросы