yapstudios / YapDatabase

YapDB is a collection/key/value store with a plugin architecture. It's built atop sqlite, for Swift & objective-c developers.
Other
3.35k stars 365 forks source link

Sample Swift Code database setup #211

Open cwhett opened 9 years ago

cwhett commented 9 years ago

I am new to iOS programming - I normally using Core Data for my work but want to use YapDatabase in an upcoming project. I have been looking at the sample files and I am getting stuck due to not being comfortable with Objective C.

I think it may be really helpful for people like me to have a true Swift app example in your example files. Just something simple that shows setting up the AppDelegate with a database that a view can read, write, delete to. If the app is written as much as possible in Swift, it will give swifty programmers a better reference.

I find translating Objective C to be time consuming and it can put beginners like me off of using your awesome project!

danthorpe commented 8 years ago

Hi, if you're looking for help at using YapDatabase from a pure Swift project, checkout YapDatabaseExtensions. To create a new database for instance you can do this:

import YapDatabase
import YapDatabaseExtensions

let database = YapDB.databaseNamed("database")

If you have your model types conform to Persistable you can read/write using simple functions like this:

let connection = database.newConnection()
connection.write(object)
if let object: MyObject = connection.readByKey("unique key") {
   // etc
}
johnteee commented 6 years ago

You can use this solution in Swift 3/Swift 4:

Objective-C <-> Swift bridge header:


@import Foundation;
@import YapDatabase;
@import YapDatabase.YapDatabaseView;
@import YapDatabase.YapDatabaseFilteredView;
@import YapDatabase.YapDatabaseSearchResultsView;
@import YapDatabase.YapDatabaseFullTextSearch;
@import YapDatabase.YapDatabaseSecondaryIndex;
extension FileManager {
    static func getDocumentsDirectoryPath(name :String) -> String {
        return NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first! + "/\(name)"
    }
}

let yapdb = YapDatabase.init(path: FileManager.getDocumentsDirectoryPath(name: "default.db"))

Credit:

@danthorpe Thanks for your great work!! I've found this solution by your project

YapDatabaseExtensions is a great project :D