2015-10-20 12 views
0

我在我的用戶界面中有標籤,它們始終顯示爲「可選(xxxxxxx)」。我該如何解決?如何解開我用於標籤的字符串?

在這裏,我做的JSON數據的本地對象:

func populateCurrentIssue() { 
    if populatingCurrentIssue { 
     return 
    } 

    populatingCurrentIssue = true 

    Alamofire.request(GWNetworking.Router.Issue).responseJSON() { response in 
     if let JSON = response.result.value { 

      dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0)) { 

       var nodeIDArray : [Int] 

       if (JSON .isKindOfClass(NSDictionary)) { 

        for node in JSON as! Dictionary<String, AnyObject> { 

         let nodeIDValue = node.0 
         var lastItem : Int = 0 

         if let issueElement : IssueElement = IssueElement(title: "init", nodeID: 0, timeStamp: 0, imageURL: "init", author: "init", issueNumber: "init", volumeNumber: "init", articleContent: "init", coverImageInteger: "init", coverImage: UIImage()) { 

          issueElement.title = node.1["title"] as! String 
          issueElement.nodeID = Int(nodeIDValue)! 


          issueElement.author = String(node.1["author"]) 

          lastItem = self.currentIssueObjects.count 


          self.currentIssueObjects.addObject(issueElement) 

          // Sorting with decreasing timestamp from top to bottom. 
          let timestampSortDescriptor = NSSortDescriptor(key: "timeStamp", ascending: false) 

          let indexPaths = (lastItem..<self.currentIssueObjects.count).map { 
           NSIndexPath(forItem: $0, inSection: 0) } 
          } 
         } 

        } 

       dispatch_async(dispatch_get_main_queue()) { 
        self.currentIssueTableView.reloadData() 

       } 

      } 

     } 

     self.populatingCurrentIssue = false 
} 
} 

在這裏,我填充我的表視圖單元格的數據:

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

    let row = indexPath.row 

    guard let cell = tableView.dequeueReusableCellWithIdentifier(CurrentIssueArticlesTableCellIdentifier, forIndexPath: indexPath) as? CurrentIssueArticlesTableViewCell else { 

     return tableView.dequeueReusableCellWithIdentifier(CurrentIssueArticlesTableCellIdentifier, forIndexPath: indexPath) as! EditorialsTableViewCell 
    } 

    if let currentIssueObject = currentIssueObjects.objectAtIndex(indexPath.row) as? IssueElement { 

     let author = currentIssueObject.author 

     let nodeID = currentIssueObject.nodeID ?? 0 

     cell.currentIssueArticlesAuthorLabel!.font = UIFont.preferredFontForTextStyle(UIFontTextStyleSubheadline) 
     cell.currentIssueArticlesAuthorLabel!.text = author 


     else { 
        } 
       } 
      } 
     } 

     else { 
     } 
    } 
    return cell 
} 

d

JSON數據:

"637": { 
"title": "Syd Editorial: The Truth Behind Disney Princesses", 
"nid": "637", 
"type": "article", 
"created": "1444923059", 
"revision_timestamp": "1444923059", 
"disqus": { 
"domain": "****domainname***** 
"url": "****the API URL***", 
"title": "Syd Editorial: The Truth Behind Disney Princesses", 
"identifier": "node/637", 
"status": false 
}, 
"image_url": null, 
"video_url": null, 
"author": "Sydney Wilson", 
"issue": "Issue 6", 
"volume": "Volume 50", 
"issue_int": "6", 
"volume_int": "50", 
"html_content": "<p>Earlier this week I was spending my time perusing facebook and generally wasting valuable time I could be using to better my life and came across a BuzzFeed article a ‘friend’ had shared: Belle Was Literally the Fucking Worst. After immediately unfriending that anonymous friend (sorry, Mom), because I don’t need that kind of negativity in my life, I carried on with my mindless internet clicking. But it nagged at the back of my mind - what could Belle, the princess praised for her smarts, and more importantly, beauty, have done to make her so hated? So I held my breath, bracing myself for the worst kind of bullshit and clicked the clickbait article, like a fish, I was hooked and they reeled me in. I’ve never spent so much time researching Disney Princesses since I wished I was one (who am I kidding, I still wish I was one).&nbsp;<br />\r\n\tGet this, Belle was actually a rich little overdramatic brat who doesn’t care at all who she hurts, and they got all that incredible insight just from the first song. She uses her beauty to get books and bully farm animals - who does she think she is, making fun of poor illiterate sheep. She is horrible to the furniture, who only want to make her stay pleasant, and then has the gall to feel victimized for getting in trouble for ignoring the rest of the giant castle to explore literally the only room she was asked to avoid. Belle is actually the fucking worst, or is she?<br />\r\n\tSo that got me wondering, are all the Disney Princesses actually horrible people in disguise. I can’t imagine there being anything wrong with them at all, but even still I decided to revisit my personal favourite Disney Princess and see if perhaps she wasn’t exactly the role model I thought she was.&nbsp;<br />\r\n\tAriel: &nbsp;「I’m, like, sixteen Dad, I’m an adult. I can do whatever I want.」&nbsp;<br />\r\n\tI’ve heard that once you start agreeing with the parents in Disney films your childhood is officially over. I must have reached that point, because if you really think about it, Ariel is just some whiney guppy who actually has no understanding of how life really works. She misses the party dedicated entirely to her, so she could ‘find treasure’ with her ‘friend’. Looks like someone ditched a family occasion to score some drugs. While high on the latest swamp drug ‘C Weed’ she falls in love with a man who belongs to an entirely different species and is surprised when her dad gets pissed of and destroys her paraphernalia.&nbsp;<br />\r\n\tI’m sure I could go on for pages about how disney princesses are actually shit, and mayhaps one day I will, but fortunately for you today is not that day. Just heed my warning, if you still want to be a disney princess, while I commend you, your priorites are shit and you should probably seek some kind of professional for your mental or drug related issues. &nbsp;&nbsp; &nbsp;</p>", 
"article_category": { 
"name": "Editorials", 
"machine_name": "editorials" 
}, 
"cover_image": "0", 
"slider_item": "0", 
"tags": [ 
"Disney", 
"Role Models" 
] 
}, 
+0

減少你的代碼到最低限度,只發布什麼是你的基本問題 – Kametrixom

+0

我清理東西了。 –

+0

你可以只發布你想打開的標籤嗎? – Lukas

回答

2

訪問字典返回可選。

這是您的node.1["author"]String()populateCurrentIssue()的情況。

解決方案:

if let author = node.1["author"] as? String { 
    issueElement.author = author 
} 
+0

我發誓愛你!它工作! –

+0

我有字面上一直試圖擺脫這個3周! –

+0

謝謝你無限花花公子 –

0

我相信你在作者部分獲得了一個可選值。如果是這樣,那麼做這個。

guard let author = currentIssueObject.author as? String else { 
print("author not found") 
return cell 
} 
+0

當我使用第一個函數時,出現錯誤「非void函數應該返回一個值」。 –

+0

當我嘗試第二個,我得到錯誤「無法將類型'NSNull'的值轉換爲'NSString'。 –

+0

我仍然得到相同的錯誤。我應該返回什麼? –

0

的可選(someText)的問題將得到解決這樣的:

guard let author = currentIssueObject.author else { 
    return 
} 

遺憾的是,當你分配一個包裹字符串.text的屬性,你沒有得到警告,可能是因爲你」允許分配零。

我看到你的代碼一些問題,不過,讓我提出一個替代方案:

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

    let row = indexPath.row 

    guard let cell = tableView.dequeueReusableCellWithIdentifier(CurrentIssueArticlesTableCellIdentifier, forIndexPath: indexPath) as? CurrentIssueArticlesTableViewCell else { 
     return tableView.dequeueReusableCellWithIdentifier(CurrentIssueArticlesTableCellIdentifier, forIndexPath: indexPath) as! EditorialsTableViewCell 
    } 

    guard currentIssueObjects.count - 1 > indexPath.row else { 
     return cell // There is no safe unwrappy way go get an object from an array, just do a boundaries check 
    } 

    let currentIssueObject = currentIssueObjects.objectAtIndex(indexPath.row) 

    guard let author = currentIssueObject.author, 
     nodeID = currentIssueObject.nodeID else { 
     return cell 
    } 

    // Always use ?. instead of !. whenever possible, or unwrap first 
    cell.currentIssueArticlesAuthorLabel?.font = UIFont.preferredFontForTextStyle(UIFontTextStyleSubheadline) 
    cell.currentIssueArticlesAuthorLabel?.text = author 

    return cell 
} 

還有更多的事情可以對你的代碼加以改進。我不認爲IssueElement作者屬性應該是一個可刪除的字符串,因爲它是通過init創建的。

同樣重要:

Alamofire.request(GWNetworking.Router.Issue).responseJSON() { [weak self] response in 
    guard strongSelf = self else { 
     return // self doesn't exist anymore when the thread returns 
    } 
+0

它仍然不起作用...它仍然說「可選()」 –

+0

所以有幾種可能性:你需要把一個斷點放在你接收數據和調試的地方,如果你從同一個應用程序保存和加載,你可能先保存了Optional(something)值,現在你要加載它時間 –

+0

作者變量只是不斷地顯示爲Optional(),即使它經過我剛添加的守衛let循環,它也不會被解開。 –

0

if let author = currentIssueObject.author { //author is unwrapped }

這:

if let nodeID = currentIssueObject.nodeID { //nodeID is unwrapped }

+0

爲第一個解決方案,我得到的錯誤「初始化條件綁定必須有可選類型,而不是'字符串' –

+0

得到它的工作。看看埃裏克D.的答案。 –