当前位置: 动力学知识库 > 问答 > 编程问答 >

ios - Prevent Realm from writing JSON twice

问题描述:

I'm new to Realm and iOS. I'm working on an app(written in Swift) that has a feature for the user to search for golf courses. I have a JSON file with roughly 18K courses in it. So I wanted to use Realm so I can quickly search through these courses in my app without it slowing down the user experience. I was able to get my JSON file written to the Realm Browser and can retrieve and search through the items, which has made it a LOT faster.

The problem I'm is I have the code in my App Delegate because I wanted to send the JSON items to my Realm Browser upon the app's launch. But if the app is started again then it writes the JSON file again, which creates duplicate golf courses in my Realm Browser.

Any suggestions on how I should do this so I can write the JSON file to the browser without getting duplicates each time the app is launched?

Thanks!

My code for writing my JSON file to my Realm Browser:

 let dataManager = DataManager.getGolfCoursesFromFileWithSuccess { (data) -> Void in

let json = JSON(data: data)

if let courseArray = json.array {

for course in courseArray {

let golfCourseName: String? = course["biz_name"].string

let city: String? = course["e_city"].string

let state: String? = course["e_state"].string

if golfCourseName != nil {

let course = Course()

course.name = golfCourseName!

course.city = city!

course.state = state!

let realm = try! Realm()

try! realm.write {

realm.add(course)

}

}

}

}

}

网友答案:

Just check to see if the data is stored already. I.e.

if try! Realm().objects(GolfCourse).count == 0 {
    // your loading code here.
}
网友答案:

I figured it out. Because this was a data set that I wanted the user to have when they initially start using the app I learned how to bundle a Realm file with this data and put the file directly in my Xcode project. I then configured this file using the method:

 "NSBundle.mainBundle().pathForResource("MyBundledData", ofType:"realm")" 
分享给朋友:
您可能感兴趣的文章:
随机阅读: