最新消息:20210816 当前crifan.com域名已被污染,为防止失联,请关注(页面右下角的)公众号

[记录]swift中尝试使用Realm数据库去保存数据

iOS crifan 2486浏览 0评论

之前已经通过Carthage 去安装了Ream的库:

github "realm/realm-cocoa"

现在需要去:

搞懂具体如何使用Realm

Realm

https://realm.io/docs/swift/latest/

Realm

https://realm.io/cn/docs/swift/latest/

发现有三种初始化的方法

现在尝试去搞懂

/**
A Realm instance (also referred to as "a realm") represents a Realm
database.
Realms can either be stored on disk (see `init(path:)`) or in
memory (see `Configuration`).
Realm instances are cached internally, and constructing equivalent Realm
objects (with the same path or identifier) produces limited overhead.
If you specifically want to ensure a Realm object is
destroyed (for example, if you wish to open a realm, check some property, and
then possibly delete the realm file and re-open it), place the code which uses
the realm within an `autoreleasepool {}` and ensure you have no other
strong references to it.
– warning: Realm instances are not thread safe and can not be shared across
           threads or dispatch queues. You must construct a new instance on each thread you want
           to interact with the realm on. For dispatch queues, this means that you must
           call it in each block which is dispatched, as a queue is not guaranteed to run
           on a consistent thread.
*/
final public class Realm {
    /// The Schema used by this realm.
    public var schema: RealmSwift.Schema { get }
    /// Returns the `Configuration` that was used to create this `Realm` instance.
    public var configuration: RealmSwift.Realm.Configuration { get }
    /// Indicates if this Realm contains any objects.
    public var isEmpty: Bool { get }
    /**
        Obtains a Realm instance with the default Realm configuration, which can be
        changed by setting `Realm.Configuration.defaultConfiguration`.
        – throws: An NSError if the Realm could not be initialized.
        */
    public convenience init() throws
    /**
        Obtains a Realm instance with the given configuration.
        – parameter configuration: The configuration to use when creating the Realm instance.
        – throws: An NSError if the Realm could not be initialized.
        */
    public convenience init(configuration: RealmSwift.Realm.Configuration) throws
    /**
        Obtains a Realm instance persisted at the specified file URL.
        – parameter fileURL: Local URL to the realm file.
        – throws: An NSError if the Realm could not be initialized.
        */
    public convenience init(fileURL: NSURL) throws

解释说明中提到了:

不支持多线程,不是线程安全的

-》需要在对应的dispatch queue中,每次都单独创建对应的realm的实例。。。

先不去管

等后期熟悉了,再去研究那个带文件路径的:fileURL

结果简单的实例都出错了:

[已解决]swift中使用realm去write出错:Cannot convert value of type to expected argument type Object

把之前的类的定义改为:

//class RegionItem:NSObject {
class RegionItem: Object {
    dynamic var id:Int = Int.InvalidId
    dynamic var code:Int = Int.InvalidId
    dynamic var name:String = ""
    dynamic var parentId:Int = Int.InvalidId
    dynamic var level:Int = 0
    dynamic var regionOrder:Int = 0
    dynamic var englishName:String = ""
    dynamic var shortName:String = ""
//    var id:Int
//    var code:Int
//    var name:String
//    var parentId:Int
//    var level:Int
//    var regionOrder:Int
//    var englishName:String
//    var shortName:String
//    init(id: Int = Int.InvalidId, code:Int = Int.InvalidId, name: String = "", parentId:Int = Int.InvalidId, level:Int = 0, regionOrder:Int = 0, englishName:String = "", shortName: String = ""){
//        self.id = id
//        self.code = code
//        self.name = name
//        self.parentId = parentId
//        self.level = level
//        self.regionOrder = regionOrder
//        self.englishName = englishName
//        self.shortName = shortName
//        
//        super.init()
//    }
    var isEmpty: Bool {
        //return (self.id <= 0) && self.code.isEmpty && self.name.isEmpty
        //return (self.id <= 0) && self.name.isEmpty
        return (!self.code.isValidId) && self.name.isEmpty
    }
    override var description: String {
        return "\(super.description),id=\(id),code=\(code),name=\(name),parentId=\(parentId),level=\(level),regionOrder=\(regionOrder),englishName=\(englishName),shortName=\(shortName)"
    }
}

之后又改为:

//class RegionItem:NSObject {
class RegionItem: Object {
    dynamic var id:Int = Int.InvalidId
    dynamic var code:Int = Int.InvalidId
    dynamic var name:String = ""
    dynamic var parentId:Int = Int.InvalidId
    dynamic var level:Int = 0
    dynamic var regionOrder:Int = 0
    dynamic var englishName:String = ""
    dynamic var shortName:String = ""
//    var id:Int
//    var code:Int
//    var name:String
//    var parentId:Int
//    var level:Int
//    var regionOrder:Int
//    var englishName:String
//    var shortName:String
//    convenience init(id: Int = Int.InvalidId, code:Int = Int.InvalidId, name: String = "", parentId:Int = Int.InvalidId, level:Int = 0, regionOrder:Int = 0, englishName:String = "", shortName: String = ""){
    convenience init(id: Int = Int.InvalidId, code:Int, name: String, parentId:Int = Int.InvalidId, level:Int = 0, regionOrder:Int = 0, englishName:String = "", shortName: String = ""){
        self.init()
        self.id = id
        self.code = code
        self.name = name
        self.parentId = parentId
        self.level = level
        self.regionOrder = regionOrder
        self.englishName = englishName
        self.shortName = shortName
//        super.init()
    }
    var isEmpty: Bool {
        //return (self.id <= 0) && self.code.isEmpty && self.name.isEmpty
        //return (self.id <= 0) && self.name.isEmpty
        return (!self.code.isValidId) && self.name.isEmpty
    }
//    override var description: String {
//        return "\(super.description),id=\(id),code=\(code),name=\(name),parentId=\(parentId),level=\(level),regionOrder=\(regionOrder),englishName=\(englishName),shortName=\(shortName)"
//    }
}

其中的:

1.convenience init

是为了别处的初始化调用:

let selectedProvinceItem = RegionItem(code: self.curCustomerItem.provinceCode, name: self.curCustomerItem.provinceName)

2.去掉了自己写的override var description: String,是因为:

Object已经默认帮我们实现了对应的debug string:

                try! realm.write {
                    realm.add(curRegionItem)
                    gLog.verbose("added \(curRegionItem) to realm db")
                }

输出了:

2016-06-25 11:08:03.855 [Verbose] [com.apple.root.background-qos] [CustomerViewController.swift:996] getRegionListHandler(_:mergedAllPara:) > added RegionItem {
    id = 32;
    code = 650000;
    name = 新疆维吾尔自治区;
    parentId = 1;
    level = 0;
    regionOrder = 0;
    englishName = Xinjiang Uygur Zizhiqu;
    shortName = XJ;
} to realm db

即,Object帮我们写好了格式化好的对象的字符串了,无需我们自己再写了。

转载请注明:在路上 » [记录]swift中尝试使用Realm数据库去保存数据

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
83 queries in 0.177 seconds, using 22.14MB memory