2015-01-13 5 views
0

방금 ​​Swift을 사용하기 시작 했으므로 JSON 파일을 구문 분석 한 결과를 UITableView에 표시하고 싶습니다. 문제는 표시 할 모든 개체가 포함될 내 NSMutableArray 뉴스 초기화로 인해 발생합니다.Swift에서 json 파일에 대한 사전 배열을 초기화하십시오.

error : "/Users/******/Documents/developper/******/******* 
/NewsTableViewController.swift:79:22: 'NSMutableArray?' 
does not have a member named 'count' 

코드는 다음과 같습니다 :

은 내가 오류가 "?"

import UIKit 

class NewsTableViewController: UITableViewController { 

var bytes: NSMutableData? 

// var news: NSArray = [] 

var news: NSMutableArray? 

override func viewDidLoad() { 
    super.viewDidLoad() 

    // Uncomment the following line to preserve selection between presentations 
    // self.clearsSelectionOnViewWillAppear = false 

    // Uncomment the following line to display an Edit button in the navigation bar for this view controller. 
    // self.navigationItem.rightBarButtonItem = self.editButtonItem() 



     // this is our remote end point (similar to URLRequest in AS3) 
    let request = NSURLRequest(URL: NSURL(string: "http://mangerdulion.com/wp-content/newsInnoven.json")!) 

    // this is what creates the connection and dispatches the varios events to track progression, etc. 
    let loader = NSURLConnection(request: request, delegate: self, startImmediately: true) 

} 
func connection(connection: NSURLConnection!, didReceiveData conData: NSData!) { 
    self.bytes?.appendData(conData) 
} 
func connection(didReceiveResponse: NSURLConnection!, didReceiveResponse response: NSURLResponse!) { 
    self.bytes = NSMutableData() 
} 

func connectionDidFinishLoading(connection: NSURLConnection!) { 

    // we serialize our bytes back to the original JSON structure 
    let jsonResult: Dictionary = NSJSONSerialization.JSONObjectWithData(self.bytes!, options: NSJSONReadingOptions.MutableContainers, error: nil) as Dictionary<String, AnyObject> 

    // we grab the colorsArray element 
    let results: NSArray = jsonResult["newsArray"] as NSArray 

    self.news?.addObjectsFromArray(results) 
    /* 
    // we iterate over each element of the colorsArray array 
    for item in results { 
     // we convert each key to a String 
     var titre: String = item["titreNews"] as String 
     var date: String = item["dateNews"] as String 
     var contenu: String = item["contenuNews"] as String 
     println("\(titre): \(date):\(contenu)") 

    } 
*/ 

} 

override func didReceiveMemoryWarning() { 
    super.didReceiveMemoryWarning() 
    // Dispose of any resources that can be recreated. 
} 

// MARK: - Table view data source 



override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
    // #warning Incomplete method implementation. 
    // Return the number of rows in the section. 

    //println(self.news?.count) 

    return self.news.count 

} 


override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 
    let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath) as UITableViewCell 




    let titre: NSDictionary = self.news[indexPath.row] as NSDictionary 

    cell.textLabel?.text = titre["titreNews"] as? String 
    println(cell.textLabel?.text) 


    // Get the formatted price string for display in the subtitle 
    let contenu: NSString = titre["contenuNews"] as NSString 

    cell.detailTextLabel?.text = contenu 


    return cell 
} 

답변

0

는 클래스의 상단에 변경 가능한 배열을 생성하고, 어떤을 넣지 마십시오을 또는 "!" 뉴스 후.

var news: NSMutableArray = [] 

는 또한 변수를 선언하는 것은 Optional 변수를 만드는 동안 클래스의 끝에서 ? 문자를 퍼팅 connectionDidFinishLoading 방법

+0

감사합니다, 지금이 부분은 작동하지만 난이 오류가 오류 = *** 어설 션 실패 - [jQuery과 dequeueReusableCellWithIdentifier "재정의 FUNC의있는 tableView (있는 tableView : NSIndexPath : jQuery과, cellForRowAtIndexPath indexPath를)"forIndexPath :], /SourceCache/UIKit_Sim/UIKit-3318.16.14/UITableView.m:6116 ** 캐치되지 않은 예외 'NSInternalInconsistencyException'으로 인해 응용 프로그램을 종료합니다. 이유 : '식별자가있는 셀을 dequeue 할 수 없습니다. reuseIdentifier - 펜촉을 등록해야합니다. 클래스를 사용하거나 스토리 보드 ' – newdeck

+0

@newdeck에 프로토 타입 셀을 연결하는 경우 스토리 보드에서 셀의 식별자를'reuseIdentifier '로 설정 했습니까? – rdelmar

0

의 말에 테이블보기에 reloadData를 호출해야합니다. Optional 변수는 nil 일 수도 있고 값이 Optional (value) 일 수도 있습니다. 옵션을 사용하려면 사용을 해제해야합니다.

var news:NSMutableArray?optional 배열을 만듭니다.

items?.count은 선택적 Optional (Int)을 반환합니다. count 메서드의 UITableView에서는 반환 할 수 없습니다.

여기서는 선택 사항을 사용할 필요가 없다고 생각합니다. 대신 빈 배열을 사용하여 편리하게 사용할 수 있습니다.

var news: NSMutableArray = []

+0

고마워, 이제이 부분은 작동하지만이 오류는 "override func tableView (tableView : UITableView, cellForRowAtIndexPath indexPath : NSIndexPath)"오류입니다. *** 어설 션 오류 - [UITableView dequeueReusableCellWithIdentifier : forIndexPath :],/SourceCache/UIKit_Sim /UIKit-3318.16.14/UITableView.m:6116 ** 캐치되지 않은 예외 'NSInternalInconsistencyException'으로 인해 응용 프로그램을 종료합니다. 이유 : '식별자가있는 셀을 dequeue 할 수 없습니다. reuseIdentifier - 식별자의 nib 또는 클래스를 등록하거나 프로토 타입을 연결해야합니다. 스토리 보드의 셀 ' – newdeck

관련 문제