Search code examples
iosswiftyapdatabase

How to save multiple entries in table using YapDatabase for swift


I am using YapDatabase for storing my objects.Need how to store multiple entries in a table.

For example : I need to save all students information in Student table. So how can I do that with YapDatabase using Swift.

var paths = NSSearchPathForDirectoriesInDomains(.CachesDirectory, .UserDomainMask, true)

    let baseDir:String = paths.count > 0 ? paths[0] as String : NSTemporaryDirectory() as String

    let path = baseDir.stringByAppendingString("Database.sqlite")

    yapDB = YapDatabase(path: path)

    yapDataBaseConection = yapDB?.newConnection()

    yapDataBaseConection?.asyncReadWriteWithBlock({ transaction in




        }, completionBlock: {


    });

Solution

  • There are plenty of examples on YapDatabase Wiki

    First of all you should make a proper class that represents your student. You can read about it in this article.

    Then you should save an array of your students to database. asyncReadWriteWithBlock is okay.

    for student in students {
        transaction.setObject(student, forKey:student.uniqueID, inCollection:"students")
    }
    

    That is all!

    Another comlex task is to sort all the students and to show them in a UITableView. To make it work you should read about View and Mappings

    If you are looking for some swift examples - you can check my sample project. It is swift 2.3 compatible.

    Hope it helps...