RealmDB没有填充

时间:2018-05-23 07:25:56

标签: swift realm

Realm的新手......希望能有一个简单的解决方案!

我有一个数据对象:

@Override
protected String doInBackground(String... strings) {
    URL url;
    HttpURLConnection urlConnection = null;

    try {
        url = new URL(strings[0]);
        urlConnection = (HttpURLConnection) url.openConnection();

        int responseCode = urlConnection.getResponseCode();

        if(responseCode == HttpURLConnection.HTTP_OK){
            server_response = readStream(urlConnection.getInputStream());
            Log.v("CatalogClient", server_response);
        }

    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return server_response;
}

在我的class GasFile : Object { @objc dynamic var gasFilename : String = "" // @objc dynamic var gasCategory : String? = "" } 我有以下功能:

ViewController

这样可以设置RealmDB,但永远不会被填充  该功能的目的是保存存储在名为func PopulateRealmWithFilenames() { let fm = FileManager.default var path = Bundle.main.resourcePath! path += "/NBTFiles" //let items = try! fm.contentsOfDirectory(atPath: path) let items : [String] = try! fm.subpathsOfDirectory(atPath: path) for item in items { do { print("item for realm is: \(item)") try self.realm.write { let newGasFile = GasFile() newGasFile.gasFilename.append(item) print("newGasFile written ok") } } catch { print("Error writing new item to Realm \(error)") } } } 的文件夹中的文件的所有文件名(而不是路径)。  我把打印好的' newGasfile打印出来'所以它进入了循环。
数据类型错误? (我知道我可以将它放入数组,但我想使用领域)

1 个答案:

答案 0 :(得分:1)

如何在不使用添加功能的情况下将新对象添加到领域? 你应该使用realm.add(object: newGasFile)

试试这个

func PopulateRealmWithFilenames() {
let fm = FileManager.default
var path = Bundle.main.resourcePath!
path += "/NBTFiles"
//let items = try! fm.contentsOfDirectory(atPath: path)
let items : [String] = try! fm.subpathsOfDirectory(atPath: path)

for item in items {


    do {
        print("item for realm is: \(item)")
        try self.realm.write {
            let newGasFile = GasFile()
            newGasFile.gasFilename.append(item)
            realm.add(object: newGasFile)
            print("newGasFile written ok")
        }
    } catch {
        print("Error writing new item to Realm \(error)")
    }
}
}
相关问题