(自我回答)Swift数组在函数numberofRows中返回0计数(在tableView中,但在其他任何地方它返回正确数量的array.count

时间:2017-06-24 00:43:44

标签: arrays swift macos count tableview

我有一个项目从Internet加载JSON文件并将其存储在数组和字典中。当我在viewDitload或viewDidDisappear中打印数组或Dict的计数时,我在JSON文件中得到正确的50个数。但是在numberOfRows和objectForValue中调用tableViewDataSource时,它会为计数返回0。我忽略了一些东西但是在打开和关闭窗口时,数组中有信息,但是当tableView以某种方式重新加载时,数组是空的。这是我的代码任何帮助非常感谢

import Cocoa

class ViewController: NSViewController, NSTableViewDataSource, NSTableViewDelegate {

    var coursesDict = [String: Course]()
    var coursesArray = [Course]()

    @IBAction func refreshTable(_ sender: Any) {
        table.reloadData()
    }
    @IBOutlet weak var table: NSTableView!

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

    func numberOfRows(in tableView: NSTableView) -> Int {

        let numOfRows = coursesArray.count
        print(numOfRows)

        return numOfRows

    }

    func tableView(_ tableView: NSTableView, objectValueFor tableColumn: NSTableColumn?, row: Int) -> Any? {
        return coursesArray[row]
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        if let data = UserDefaults.standard.data(forKey: "courses"),
            let savedCourses = NSKeyedUnarchiver.unarchiveObject(with: data) as? [String: Course] {
            self.coursesDict = savedCourses
            loadDataFromURL()

            self.coursesArray = Array(coursesDict.values)
            print(coursesDict.count, " appLaunch")
        } else {
            print("There is an issue")
        }
    }

        override var representedObject: Any? {
        didSet {
        // Update the view, if already loaded.
        }
    }

    override func viewDidDisappear() {
        let encodedData = NSKeyedArchiver.archivedData(withRootObject: coursesDict)
        UserDefaults.standard.set(encodedData, forKey: "courses")
        print(coursesDict.count, "viewUnload")
    }

    func loadDataFromURL() {
        // Fetch URL
        let url = URL(string: "https://www.apple.com/nl/today/static/data/hub/1101000001001110001.json")!

        // Load Data
        let data = try! Data(contentsOf: url)

        // Deserialize JSON
        let json = try! JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String: AnyObject]

        let coursesJSON = json?["courses"] as? [AnyObject]

        for object in coursesJSON! {
            let id = object["id"] as! String
            if coursesDict[id] == nil {
                let name = object["shortName"] as! String
                let program = object["programName"] as! String
                let shortDescription = object["shortDesc"] as! String
                let mediumDescription = object["mediumDesc"] as! String
                let longDescription = object["longDesc"] as! String
                let imageURL = object["image"] as! String

                let tempCourse = Course(id: id, name: name, program: program, shortDescription: shortDescription, mediumDescription: mediumDescription, longDescription: longDescription, imageURL: imageURL)

                coursesDict[id] = tempCourse
            }
        }
        print(coursesDict.count, "loadURL")
    }

}

我甚至在我的视图上有一个按钮,重新加载tableView,以防在tableView重新加载之前未加载信息

3 个答案:

答案 0 :(得分:0)

我猜在从互联网上检索数据之前,正在调用numberOfRows。解决这个问题的一种方法是在coursesArray中设置一个监听器,尝试替换它:

var coursesArray: [Course] = []

有了这个:

var coursesArray: [Course] = [] {
    didSet {
        table.reloadData()
    }
}

答案 1 :(得分:0)

namespace HashSet
{
    public class Employe
    {
        public Employe() {
        }

        public string Name { get; set; }

        public override string ToString()  {
            return Name;
        }

        public override bool Equals(object obj) {
            return this.Name.Equals(((Employe)obj).Name);
        }

        public override int GetHashCode() {
            return this.Name.GetHashCode();
        }
    }

    class EmployeComparer : IEqualityComparer<Employe>
    {
        public bool Equals(Employe x, Employe y)
        {
            return x.Name.Trim().ToLower().Equals(y.Name.Trim().ToLower());
        }

        public int GetHashCode(Employe obj)
        {
            return obj.Name.GetHashCode();
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            HashSet<Employe> hashSet = new HashSet<Employe>(new EmployeComparer());
            hashSet.Add(new Employe() { Name = "Nik" });
            hashSet.Add(new Employe() { Name = "Rob" });
            hashSet.Add(new Employe() { Name = "Joe" });
            Display(hashSet);
            hashSet.Add(new Employe() { Name = "Rob" });
            Display(hashSet);

            HashSet<Employe> hashSetB = new HashSet<Employe>(new EmployeComparer());
            hashSetB.Add(new Employe() { Name = "Max" });
            hashSetB.Add(new Employe() { Name = "Solomon" });
            hashSetB.Add(new Employe() { Name = "Werter" });
            hashSetB.Add(new Employe() { Name = "Rob" });
            Display(hashSetB);

            var union = hashSet.Union<Employe>(hashSetB).ToList();
            Display(union);
            var inter = hashSet.Intersect<Employe>(hashSetB).ToList();
            Display(inter);
            var except = hashSet.Except<Employe>(hashSetB).ToList();
            Display(except);

            Console.ReadKey();
        }

        static void Display(HashSet<Employe> hashSet)
        {
            if (hashSet.Count == 0)
            {
                Console.Write("Collection is Empty");
                return;
            }
            foreach (var item in hashSet)
            {
                Console.Write("{0}, ", item);
            }
            Console.Write("\n");
        }

        static void Display(List<Employe> list)
        {
            if (list.Count == 0)
            {
                Console.WriteLine("Collection is Empty");
                return;
            }
            foreach (var item in list)
            {
                Console.Write("{0}, ", item);
            }
            Console.Write("\n");
        }
    }
}

答案 2 :(得分:0)

问题不在于我的代码。问题在于我在我的Xib中有两个viewController实例,所以当我将数据硬编码到数组中时,它正在工作,因为两个实例都有这个信息,但第二个viewcontroller的viewDidload从未被调用,因为它是没有连接到任何视图