Unrealm is an extension on RealmCocoa, which enables Swift native types to be saved in Realm.

Overview

Unrealm Header Logo



Swift 5.1 Build Status Version Platform License Platform Platform


Unrealm enables you to easily store Swift native Classes, Structs and Enums into Realm .
Stop inheriting from Object! Go for Protocol-Oriented programming!
Made with ❤️ by arturdev



Features

Unrealm supports the following types:

  • Swift Primitives
  • Swift Structs
  • Swift Classes
  • Swift Enums
  • Swift Arrays
  • Swift Dictionaries
  • Nested Classes/Structs
  • Swift Optionals (String, Data, Date)
  • Swift Optionals of primitives (Int, Float, Double, Bool)
  • Swift Optionals of Realmables
  • Swift Optionals of Arrays
  • Swift Arrays of enums

Example Project

To run the example project, clone the repo, and run pod install from the Example directory first.
See also Unit Tests.

Usage

All you have to do is

  1. Conform your Classes/Structs to Realmable protocol instead of inheriting from Object. Conform your Enums to RealmableEnum protocol.
  2. Register your Classes/Structs and Enums in AppDelegate's didFinishLaunchingWithOptions.
Realm.registerRealmables(ToDoItem.self)

Thats it! Now you can store your Struct or Class object into Realm as usualy you do with Objc Classes.

Pros and Cons

Pros 🎉

  • Enables you to store Swift native types (Structs, Classes, Enums, Arrays, Dictionaries, etc...)
  • Getting rid of redundant inheriting from Object class
  • Getting rid of Realm crashes like "Object has been deleted or invalidated"
  • Getting rid of Realm crashes like "Realm accessed from incorrect thread"
  • Getting rid of boilerplate code such as @objc dynamic var. Use just var or let
  • Getting rid of boilerplate code such as RealmOptional<Int>. Use just Int?
  • Works perfect with Swift's Codable and optional types!

Cons 🍟

  • Losing "Live Objects" feature. Which means when you modify an object got from Realm the other ones will not be updated automatically. So after modifying an object you should manually update it in realm. f.e.;
let realm = try! Realm()
var todoItem = realm.object(ofType: ToDoItem.self, forPrimaryKey: "1")
todoItem.text = "Modified text"
try! realm.write {
realm.add(todoItem, update: true) //<- force Realm to update the object
}

Installation

CocoaPods

Unrealm is available through CocoaPods. To install it, simply add the following line to your Podfile:

pod 'Unrealm'

Swift Package Manager

You can also use Swift Package Manager to add Unrealm as a dependency to your project. In order to do so, use the following URL:

https://github.com/arturdev/Unrealm.git

You need to use "SPM" branch instead of master.

ToDos

  • Add more UnitTests
  • Create a sample project for Swift Package Manager when dependencies can be added to many targets in a simple project.

Contribution

⭐️ If you like what you see, star us on GitHub.

Find a bug, a typo, or something that’s not documented well? We’d love for you to open an issue telling me what I can improve!

Contributions are welcome, and they are greatly appreciated!

Author

arturdev, [email protected]

License

Unrealm is available under the MIT license. See the LICENSE file for more info.

Comments
  • error: Unexpectedly found nil while unwrapping an Optional value

    error: Unexpectedly found nil while unwrapping an Optional value

    let cls = (NSClassFromString(realmClass) ?? NSClassFromString(realmTypeName)) as! Object.Type
    

    error: Unexpectedly found nil while unwrapping an Optional value

    opened by ahmadmssm 22
  • Question: Does Unrealm support Realm objects with optional properties?

    Question: Does Unrealm support Realm objects with optional properties?

    Question: Does Unrealm support Realm objects with optional properties? e.g. struct Jukugo: Realmable { public let id: Int? = 0 public let nameString: String? = "" public let address: String? = "" public let pinCode: Int? = 0

    static func primaryKey() -> String? { return "id" } }

    opened by lingolab2 15
  • How to deal with this crash?

    How to deal with this crash?

    I have an app crashing every time when I'm trying to save one data type. I have no problems with others. Is there a way to find out what is causing it and how to change my data struct to fix it?

    Here's a crash log:

    2019-10-31 20:21:14.672690+0200 App Name[48103:1190682] *** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<RLM:Unmanaged RLMProductFields 0x600002307d90> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key description.'
    *** First throw call stack:
    (
    	0   CoreFoundation                      0x00007fff23baa1ee __exceptionPreprocess + 350
    	1   libobjc.A.dylib                     0x00007fff50864b20 objc_exception_throw + 48
    	2   CoreFoundation                      0x00007fff23ba9db9 -[NSException raise] + 9
    	3   Realm                               0x000000010759394c -[RLMObjectBase setValue:forUndefinedKey:] + 1100
    	4   Foundation                          0x00007fff2563e130 -[NSObject(NSKeyValueCoding) setValue:forKey:] + 325
    	5   Unrealm                             0x0000000108fa85a2 $s7Unrealm7convert33_C4ACF08D0134400842049C7DF7DCE9DDLL3val2toyXlSgyp_xmtSo8NSObjectCRbzlFySSSg5label_yp5valuet_tXEfU0_ + 7570
    	6   Unrealm                             0x0000000108faa19b $sSSSgyps5Error_pIggnzo_AA5label_yp5valuetsAB_pIegnzo_TR + 59
    	7   Unrealm                             0x0000000108fab1c4 $sSSSgyps5Error_pIggnzo_AA5label_yp5valuetsAB_pIegnzo_TRTA + 20
    	8   libswiftCore.dylib                  0x00007fff50e6b024 $sSTsE7forEachyyy7ElementQzKXEKF + 452
    	9   Unrealm                             0x0000000108fa2052 $s7Unrealm7convert33_C4ACF08D0134400842049C7DF7DCE9DDLL3val2toyXlSgyp_xmtSo8NSObjectCRbzlF + 658
    	10  Unrealm                             0x0000000108fa75a8 $s7Unrealm7convert33_C4ACF08D0134400842049C7DF7DCE9DDLL3val2toyXlSgyp_xmtSo8NSObjectCRbzlFySSSg5label_yp5valuet_tXEfU0_ + 3480
    	11  Unrealm                             0x0000000108faa19b $sSSSgyps5Error_pIggnzo_AA5label_yp5valuetsAB_pIegnzo_TR + 59
    	12  Unrealm                             0x0000000108fab1c4 $sSSSgyps5Error_pIggnzo_AA5label_yp5valuetsAB_pIegnzo_TRTA + 20
    	13  libswiftCore.dylib                  0x00007fff50e6b024 $sSTsE7forEachyyy7ElementQzKXEKF + 452
    	14  Unrealm                             0x0000000108fa2052 $s7Unrealm7convert33_C4ACF08D0134400842049C7DF7DCE9DDLL3val2toyXlSgyp_xmtSo8NSObjectCRbzlF + 658
    	15  Unrealm                             0x0000000108fa1cb7 $s7Unrealm9RealmablePAAE8toObject10RealmSwift0D0CSgyF + 247
    	16  App Name                            0x0000000105708197 $s18App_Name7ProductV7Unrealm13RealmableBaseAadEP8toObject10RealmSwift0H0CSgyFTW + 39
    	17  Unrealm                             0x0000000108f9295d $s10RealmSwift0A0C7UnrealmE3add_6updateyx_AC12UpdatePolicyOtAD9RealmableRzlF + 189
    	18  Unrealm                             0x0000000108f92e0b $s10RealmSwift0A0C7UnrealmE3add_6updateyx_SbtSTRzAD9Realmable7ElementRpzlF + 715
    	19  App Name                            0x0000000105a6a489 $s18App_Name14ProductFetcherC5cache33_7573542C37BF51E4E44F88A166B84251LLyySayAA0C0VGFyyXEfU_ + 105
    	20  RealmSwift                          0x0000000108db4b63 $s10RealmSwift0A0C5writeyyyyKXEKF + 83
    	21  App Name                            0x0000000105a6a043 $s18App_Name14ProductFetcherC5cache33_7573542C37BF51E4E44F88A166B84251LLyySayAA0C0VGF + 291
    ...
    

    The function where it crashes:

    	private func cache(_ products: [ProductFields]) {
    		let realm = try! Realm()
    		do {
    			try realm.write {
    				realm.add(products, update: true)
    			}
    		} catch {
    			print("Failed to cache ProductFields. \(error.localizedDescription)")
    		}
    	}
    

    Here's a struct:

    struct ProductFields: Codable, Identifiable, Hashable, Realmable {
    	var id: String = ""
    	var name: String = ""
    	var category: [String] = []
    	var categoryName: [String] = []
    	var categoryIconTypeRaw: [String] = []
    	var description: String? = nil
    	var duration: Double? = nil
    	var guideSpeaks: [String]? = nil
    	var included: [String]? = nil
    	var availability: String? = nil
    	var shortDescription: String? = nil
    	var maxNumberOfParticipants: Int? = nil
    	var isOfferedInHotelOptional: Bool? = nil
    	var reservationNotes: String? = nil
    	var priceIsFixedOptional: Bool? = nil
    	var price: Double? = nil
    	var pricePer: String? = nil
    	var currency: String? = nil
    	var ctaTextRaw: String? = nil
    	var ctaLink: String? = nil
    	var mainImage: [AppImage] = [] // <-- AppImage is also Realmable, and it works well embedded in other structs
    
    	enum CodingKeys: String, CodingKey {
    		case name = "Name"
    		case category = "Category"
    		case categoryName = "Category Name"
    		case categoryIconTypeRaw = "Category Icon Type"
    		case description = "Description"
    		case duration = "Duration"
    		case guideSpeaks = "Guide Speaks"
    		case included = "Included"
    		case availability = "Availability"
    		case shortDescription = "Short Description"
    		case maxNumberOfParticipants = "Max Number of Participants"
    		case isOfferedInHotelOptional = "Is Offered in Hotel"
    		case reservationNotes = "Reservation Notes"
    		case priceIsFixedOptional = "Price is Fixed"
    		case price = "Price"
    		case pricePer = "Price Per"
    		case currency = "Currency"
    		case ctaTextRaw = "CTA Text"
    		case ctaLink = "CTA Link"
    		case id = "Record ID"
    		case mainImage = "Main Image"
    	}
    	
    	// A set of calculated properties, I've added them all to ignoredProperties below
    	var categories {...}
    	var numberOfParticipantsFormatted {...}
    	var durationFormatted {...}
    	var ctaText {...}
    	var ctaURL {...}
    	var categoryType {...}
    	var isOfferedInHotel {...}
    	var priceIsFixed {...}
    	var priceString {...}
    	var priceFullString {...}
    	
    	static func primaryKey() -> String? { "id" }
    	static func ignoredProperties() -> [String] {
    		[
    			"priceString",
    			"priceFullString",
    			"priceIsFixed",
    			"isOfferedInHotel",
    			"categories",
    			"categoryType",
    			"ctaText",
    			"ctaURL",
    			"durationFormatted",
    			"numberOfParticipantsFormatted"
    		]
    	}
    }
    

    I have all needed classes initialised in didFinishLaunchingWithOptions:

    		Realm.registerRealmables(
    			...
    			AppImage.self,
    			ProductFields.self
    		)
    
    opened by qizh 11
  • Is it possible to save a swift array of enums?

    Is it possible to save a swift array of enums?

    I'm getting this error

    Terminating app due to uncaught exception 'RLMException', reason: 'Property 'actions' is of type 'RLMArray' which is not a supported RLMArray object type. RLMArrays can only contain instances of RLMObject subclasses. See https://realm.io/docs/objc/latest/#to-many for more information.'

    my property actions is defined as this:

    var actions: [Action] = []

    in a Realmable struct. Action is an enum that conforms to RealmableEnum

    Any ideas?

    opened by martinstoyanov 8
  • Realm program crashes while opening realm database

    Realm program crashes while opening realm database

    program crashes when trying to open realm database.

    		let config = Realm.Configuration(fileURL: destinationURL,
    										 readOnly: false,
    										 schemaVersion: 1,
    										 migrationBlock: { (migration, oldSchemaVersion) in
    											if (oldSchemaVersion < 1) {
    
    											}
    		})
    		let realm: Realm = {
    			return try! Realm(configuration: config)
    		}()
    
    

    _The debugger gives me a hint that it is in the object table Kanji and near column kunYomis_

    struct Kanji: Realmable {
      var id: Int = 0
      var kanjiCharacter: String = ""
      var hexUnicode: String = ""
      var frequency: Int = 0
      var jlptLevel: Int = 0
      var gradeJA: Int = 0
      var strokeCount:Int = 0
      var classification: String = ""
      var kunYomis = [String]()
      var onYomis = [String]()
      var longMeanings = [String]()
      var shortMeanings = [String]()
      var radicalComponentCount: Int = 0
      var radicalComponentStrings = [String]()
      static func primaryKey() -> String?
      {
        return "id"
      }
    
    }
    
    

    This is the definition of the database as shown by RealmStudio when generating Swift model definition

    class RLMKanji: Object {
        @objc dynamic var id: Int = 0
        @objc dynamic var kanjiCharacter: String = ""
        @objc dynamic var hexUnicode: String = ""
        @objc dynamic var frequency: Int = 0
        @objc dynamic var jlptLevel: Int = 0
        @objc dynamic var gradeJA: Int = 0
        @objc dynamic var strokeCount: Int = 0
        @objc dynamic var classification: String = ""
        let kunYomis = List<String>()
        let onYomis = List<String>()
        let longMeanings = List<String>()
        let shortMeanings = List<String>()
        @objc dynamic var radicalComponentCount: Int = 0
        let radicalComponentStrings = List<String>()
    
        override static func primaryKey() -> String? {
            return "id"
        }
    }
    
    

    Have been at it since yesterday, couldn't figure out what could be wrong. Able to open the database with RealmStudio and all the data appears correct. I'm assuming that this is not a problem with Realm itself but in my definitions but can't figure out. There are three other objects in the database as well.

    .../Library/Developer/Xcode/DerivedData/JukugoExample-dswqnefsbrxzlpehxzpaxosvetds/SourcePackages/checkouts/realm-core/src/realm/table.cpp:3050: [realm-core-5.23.8] Assertion failed: get_real_column_type(col_ndx) == col_type_String || get_real_column_type(col_ndx) == col_type_StringEnum [5, 2, 5, 3] 0 JukugoExample 0x0000000106db041f _ZN5realm4utilL18terminate_internalERNSt3__118basic_stringstreamIcNS1_11char_traitsIcEENS1_9allocatorIcEEEE + 31 1 JukugoExample 0x0000000106db06d3 _ZN5realm4util9terminateEPKcS2_lOSt16initializer_listINS0_9PrintableEE + 243 2 JukugoExample 0x0000000106d1fac0 ZN5realm4util9terminateIJNS_10ColumnTypeES2_S2_S2_EEEvPKcS4_lDpT + 240 3 JukugoExample 0x0000000106d1f890 _ZNK5realm5Table3getINS_10StringDataEEET_mm + 320 4 JukugoExample 0x0000000106652aa5 _ZNK5realm5Table10get_stringEmm + 37 5 JukugoExample 0x000000010665fc38 _ZZN12_GLOBAL__N_120copy_property_valuesERKN5realm8PropertyERNS0_5TableEENK3$0clIMS4_KFNS0_10StringDataEmmEMS4_FvmmS8_bEEEDaT_T0 + 408 6 JukugoExample 0x000000010665efa5 _ZN12_GLOBAL__N_120copy_property_valuesERKN5realm8PropertyERNS0_5TableE + 501 7 JukugoExample 0x0000000106656f14 _ZN12_GLOBAL__N_122make_property_optionalERN5realm5GroupERNS0_5TableENS0_8PropertyE + 84 8 JukugoExample 0x000000010665dbd0 _ZZL27apply_pre_migration_changesRN5realm5GroupERKNSt3__16vectorINS_12SchemaChangeENS2_9allocatorIS4_EEEEEN7ApplierclENS_13schema_change20MakePropertyNullableE + 112 9 JukugoExample 0x000000010665d89f ZNK5realm12SchemaChange5visitIRZL27apply_pre_migration_changesRNS_5GroupERKNSt3__16vectorIS0_NS4_9allocatorIS0_EEEEE7ApplierEEDaOT + 367 10 JukugoExample 0x0000000106654bc3 _ZL27apply_pre_migration_changesRN5realm5GroupERKNSt3__16vectorINS_12SchemaChangeENS2_9allocatorIS4_EEEE + 115 11 JukugoExample 0x0000000106654322 _ZN5realm11ObjectStore20apply_schema_changesERNS_5GroupEyRNS_6SchemaEyNS_10SchemaModeERKNSt3__16vectorINS_12SchemaChangeENS6_9allocatorIS8_EEEENS_4util8OptionalINS6_12basic_stringIcNS6_11char_traitsIcEENS9_IcEEEEEENS6_8functionIFvvEEE + 626 12 JukugoExample 0x000000010668f679 ZN5realm5Realm13update_schemaENS_6SchemaEyNSt3__18functionIFvNS2_10shared_ptrIS0_EES5_RS1_EEENS3_IFvS5_EEEb + 1385 13 JukugoExample 0x00000001067d61fd +[RLMRealm realmWithConfiguration:error:] + 3469 14 JukugoExample 0x0000000106e02ce0 $sSo8RLMRealmC13configurationABSo0A13ConfigurationC_tKcfCTO + 144 15 JukugoExample 0x0000000106e02ede $s10RealmSwift0A0V13configurationA2C13ConfigurationV_tKcfC + 94 16 JukugoExample 0x00000001065590ef $s13JukugoExample11AppDelegateC18initializeDatabaseyyF10RealmSwift0G0VyXEfU0 + 63 17 JukugoExample 0x000000010655899a $s13JukugoExample11AppDelegateC18initializeDatabaseyyF + 1114 18 JukugoExample 0x0000000106557ef7 $s13JukugoExample11AppDelegateC11application_29didFinishLaunchingWithOptionsSbSo13UIApplicationC_SDySo0k6LaunchJ3KeyaypGSgtF + 103 19 JukugoExample 0x0000000106557fe3 $s13JukugoExample11AppDelegateC11application_29didFinishLaunchingWithOptionsSbSo13UIApplicationC_SDySo0k6LaunchJ3KeyaypGSgtFTo + 211 20 UIKitCore 0x00007fff48c0fecc -[UIApplication _handleDelegateCallbacksWithOptions:isSuspended:restoreState:] + 232 21 UIKitCore 0x00007fff48c1186b -[UIApplication _callInitializationDelegatesWithActions:forCanvas:payload:fromOriginatingProcess:] + 3985 22 UIKitCore 0x00007fff48c1742d -[UIApplication _runWithMainScene:transitionContext:completion:] + 1226 23 UIKitCore 0x00007fff48322a9a -[_UISceneLifecycleMultiplexer completeApplicationLaunchWithFBSScene:transitionContext:] + 179 24 UIKitCore 0x00007fff48c1391b -[UIApplication _compellApplicationLaunchToCompleteUnconditionally] + 59 25 UIKitCore 0x00007fff48c13c1a -[UIApplication _run] + 754 26 UIKitCore 0x00007fff48c19220 UIApplicationMain + 1605 27 JukugoExample 0x000000010655a0fb main + 75 28 libdyld.dylib 0x00007fff519b910d start + 1 29 ??? 0x0000000000000001 0x0 + 1!!! IMPORTANT: Please send this log and info about Realm SDK version and other relevant reproduction info to [email protected] 15:46:54.297867+0530 JukugoExample[6741:129825] .../Library/Developer/Xcode/DerivedData/JukugoExample-dswqnefsbrxzlpehxzpaxosvetds/SourcePackages/checkouts/realm-core/src/realm/table.cpp:3050: [realm-core-5.23.8] Assertion failed: get_real_column_type(col_ndx) == col_type_String || get_real_column_type(col_ndx) == col_type_StringEnum [5, 2, 5, 3] 0 JukugoExample 0x0000000106db041f _ZN5realm4utilL18terminate_internalERNSt3__118basic_stringstreamIcNS1_11char_traitsIcEENS1_9allocatorIcEEEE + 31 1 JukugoExample 0x0000000106db06d3 _ZN5realm4util9terminateEPKcS2_lOSt16initializer_listINS0_9PrintableEE + 243 2 JukugoExample 0x0000000106d1fac0 ZN5realm4util9terminateIJNS_10ColumnTypeES2_S2_S2_EEEvPKcS4_lDpT + 240 3 JukugoExample 0x0000000106d1f890 _ZNK5realm5Table3getINS_10StringDataEEET_mm + 320 4 JukugoExample 0x0000000106652aa5 _ZNK5realm5Table10get_stringEmm + 37 5 JukugoExample 0x000000010665fc38 _ZZN12_GLOBAL__N_120copy_property_valuesERKN5realm8PropertyERNS0_5TableEENK3$0clIMS4_KFNS0_10StringDataEmmEMS4_FvmmS8_bEEEDaT_T0 + 408 6 JukugoExample 0x000000010665efa5 _ZN12_GLOBAL__N_120copy_property_valuesERKN5realm8PropertyERNS0_5TableE + 501 7 JukugoExample 0x0000000106656f14 _ZN12_GLOBAL__N_122make_property_optionalERN5realm5GroupERNS0_5TableENS0_8PropertyE + 84 8 JukugoExample 0x000000010665dbd0 _ZZL27apply_pre_migration_changesRN5realm5GroupERKNSt3__16vectorINS_12SchemaChangeENS2_9allocatorIS4_EEEEEN7ApplierclENS_13schema_change20MakePropertyNullableE + 112 9 JukugoExample 0x000000010665d89f ZNK5realm12SchemaChange5visitIRZL27apply_pre_migration_changesRNS_5GroupERKNSt3__16vectorIS0_NS4_9allocatorIS0_EEEEE7ApplierEEDaOT + 367 10 JukugoExample 0x0000000106654bc3 _ZL27apply_pre_migration_changesRN5realm5GroupERKNSt3__16vectorINS_12SchemaChangeENS2_9allocatorIS4_EEEE + 115 11 JukugoExample 0x0000000106654322 _ZN5realm11ObjectStore20apply_schema_changesERNS_5GroupEyRNS_6SchemaEyNS_10SchemaModeERKNSt3__16vectorINS_12SchemaChangeENS6_9allocatorIS8_EEEENS_4util8OptionalINS6_12basic_stringIcNS6_11char_traitsIcEENS9_IcEEEEEENS6_8functionIFvvEEE + 626 12 JukugoExample 0x000000010668f679 ZN5realm5Realm13update_schemaENS_6SchemaEyNSt3__18functionIFvNS2_10shared_ptrIS0_EES5_RS1_EEENS3_IFvS5_EEEb + 1385 13 JukugoExample 0x00000001067d61fd +[RLMRealm realmWithConfiguration:error:] + 3469 14 JukugoExample 0x0000000106e02ce0 $sSo8RLMRealmC13configurationABSo0A13ConfigurationC_tKcfCTO + 144 15 JukugoExample 0x0000000106e02ede $s10RealmSwift0A0V13configurationA2C13ConfigurationV_tKcfC + 94 16 JukugoExample 0x00000001065590ef $s13JukugoExample11AppDelegateC18initializeDatabaseyyF10RealmSwift0G0VyXEfU0 + 63 17 JukugoExample 0x000000010655899a $s13JukugoExample11AppDelegateC18initializeDatabaseyyF + 1114 18 JukugoExample 0x0000000106557ef7 $s13JukugoExample11AppDelegateC11application_29didFinishLaunchingWithOptionsSbSo13UIApplicationC_SDySo0k6LaunchJ3KeyaypGSgtF + 103 19 JukugoExample 0x0000000106557fe3 $s13JukugoExample11AppDelegateC11application_29didFinishLaunchingWithOptionsSbSo13UIApplicationC_SDySo0k6LaunchJ3KeyaypGSgtFTo + 211 20 UIKitCore 0x00007fff48c0fecc -[UIApplication _handleDelegateCallbacksWithOptions:isSuspended:restoreState:] + 232 21 UIKitCore 0x00007fff48c1186b -[UIApplication _callInitializationDelegatesWithActions:forCanvas:payload:fromOriginatingProcess:] + 3985 22 UIKitCore 0x00007fff48c1742d -[UIApplication _runWithMainScene:transitionContext:completion:] + 1226 23 UIKitCore 0x00007fff48322a9a -[_UISceneLifecycleMultiplexer completeApplicationLaunchWithFBSScene:transitionContext:] + 179 24 UIKitCore 0x00007fff48c1391b -[UIApplication _compellApplicationLaunchToCompleteUnconditionally] + 59 25 UIKitCore 0x00007fff48c13c1a -[UIApplication _run] + 754 26 UIKitCore 0x00007fff48c19220 UIApplicationMain + 1605 27 JukugoExample 0x000000010655a0fb main + 75 28 libdyld.dylib 0x00007fff519b910d start + 1 29 ??? 0x0000000000000001 0x0 + 1!!! IMPORTANT: Please send this log and info about Realm SDK version and other relevant reproduction info to [email protected]. (lldb) Screenshot 2020-05-17 at 15 58 34

    opened by lingolab2 7
  • How to fetch swift dictionary stored in realm ?

    How to fetch swift dictionary stored in realm ?

    I have this field in a struct Contact.

    var customFields: [String: String?]?

    I'm able to store this field in realm. It is storing as data field.

    But when I try to fetch the contact and read it, the custom fields are empty.

    Do I have to manually convert data. back into swift dicionary ?

    At which level, do I have to do this conversion ?

    Info:

    At the line:

      let results = self.objects(cls)
    

    when I do, po results.first, I can see the customField with some data in it.

    customFields = <length = 24, bytes = 0x62706c6973743030d4010203040506070a58247665727369 — 1537 total bytes>;

    Now after Results(rlmResult: results) happens,

    the struct shows customFields as nil.

    Not sure how I intercept and do the conversion of data to dictionary.

    Update:

    Able to get it by tweaking a part of the code.

    if let data = value as? Data { 
    
       //works
    if let json = try NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(data) {
                                       try property.set(value: json, on: &self)
                                   }
    
    }
    

    For some reason child.value is [AnyHashable:Any] is nil and this condition fails .

    opened by Venkata-Maniteja 7
  • Installing as a SwiftPackage fails

    Installing as a SwiftPackage fails

    Tried Installing by adding this line: .package(url: "https://github.com/arturdev/Unrealm", from: "1.0.1")

    or this (since the line above does not use the latest version that includes Realm 4.3.0)

    .package(url: "https://github.com/arturdev/Unrealm", .branch("master"))

    image
    opened by JARMourato 6
  • CGFloat, CGPoint, CGSize.. tuples ?

    CGFloat, CGPoint, CGSize.. tuples ?

    Hey there,

    I am trying to have a simple struct to be Realmable...

    struct Sprite: Realmable {
        let id: String
        let position: CGPoint
        let size: CGSize
        let alpha: CGFloat
      
        static fun primaryKey() -> String { "id" }
    }
    

    I am adding extension RealmableEnum on each of these, matching Float, tried with NSNumber(cgPoint: ) and with NSCoder.string(cgPoint:).. is there a way to do so ?

    Or should I basically just save JSON strings for each object, generated by Codable ?.. sounds less efficient to me

    opened by quentinfasquel 5
  • Problem with NSKeyedArchiver

    Problem with NSKeyedArchiver

    Hi,

    I'm trying to save a simple model to the Realm, but somehow, the new version using NsKeyedArchiver is throwing an exception.

    Error Domain=NSCocoaErrorDomain Code=4866 "The data couldn’t be written because it isn’t in the correct format." UserInfo={NSUnderlyingError=0x60000168e8e0 {Error Domain=NSCocoaErrorDomain Code=4864 "This decoder will only decode classes that adopt NSSecureCoding. Class '__SwiftValue' does not adopt it." UserInfo={NSDebugDescription=This decoder will only decode classes that adopt NSSecureCoding. Class '__SwiftValue' does not adopt it.}}}

    Here's and exemple of the model I'm trying to save.

    `struct Model: Realmable, Codable {

    var id: String = UUID().uuidString
    var name: String = ""
    var cat: String = "default"
    
    var type: String = "user"
    
    var dictionary: [Int: [SomeArray]] = [:]
    
    var startDate: Date?
    var endDate: Date?
    
    static func primaryKey() -> String? {
        return "id"
    }
    

    }`

    It will save the model, but the dictionary variable will be nil.

    I'm stuck there, I have tried many different solution but I won't work.

    Thanks !

    opened by TheLuckyWan 5
  • Problem with JSONSerialization with Int as key

    Problem with JSONSerialization with Int as key

    Hello, I'm migrating my Object models to Realmable, but I have a problem with a data type I'm trying to save.

    I have a data model defined like this :

    ` struct WorkoutRoutine: Realmable, Codable {

    var id: String = UUID().uuidString
    var name: String = ""
    var bodyPart: String = ""
    
    var type: String = "normal"
    var globalRestTimer: Double = 0.0
    var exerciseSpecificRestTimer: [Int: Double] = [0: 0.0]
    
    var exercises: [Exercise]?
    var exercisesTargetSets: [Int: Int] = [0:0]
    var exercisesTargetReps: [Int: Int] = [0:0]
    
    var createdAt: Date = Date()
    
    static func primaryKey() -> String? {
        return "id"
    
    }
    

    }`

    It crashes when it's trying to serialize my object as JSON. I think it's due to the fact that the keys are required to be of type NSString (when serializing with JSONSerialization), and I'm using "Int". How could they be converted automatically?

    I'm not sure how to convert it to a string. When I take my model and encode it using JSONEncoder, it produces valid JSON.

    Here are some screenshot of the Exception Breakpoint:

    Screen Shot 2020-02-01 at 3 40 21 PM Screen Shot 2020-02-01 at 3 40 21 PM Screen Shot 2020-02-01 at 3 44 38 PM

    opened by TheLuckyWan 5
  • LinkingObjects support?

    LinkingObjects support?

    Is there a way to use LinkingObjects?

    LinkingObjects expects an Object type.

    Happy to help implement this, I imagine it would require wrapping LinkingObjects to be compatible with Realmable instead of Object.

    opened by jondwillis 5
  • RealmableEnum not able to determine RawValue

    RealmableEnum not able to determine RawValue

    I'm having a crash that reads:

    *** Terminating app due to uncaught exception 'RLMException', reason: 'Property 'enumType' is declared as 'MyEnum', which is not a supported RLMObject property type. All properties must be primitives, NSString, NSDate, NSData, NSNumber, RLMArray, RLMSet, RLMDictionary, RLMLinkingObjects, RLMDecimal128, RLMObjectId, or subclasses of RLMObject. See https://realm.io/docs/objc/latest/api/Classes/RLMObject.html for more information.'
    

    I suspect it's because I have this init in MyEnum which I can't change (because it's used in other targets I don't have access to). What could be the cause? I spent some time trying to determine the issue and discovered that inside the Realm framework on (BOOL)setTypeFromRawType:(NSString *)rawType in RLMProperty rawType is @\MyEnum\ which is wrong because all others are some variation of ObjC primitive types.

    Here's my enum code:

    public enum MyEnum: String, RealmableEnum {
        case blue
        case red
        case unknown
        
        // MARK: - Initialization
        
        public init(rawValue: String) {
            let lowercased: String = rawValue.lowercased()
            switch lowercased {
                case Self.red.rawValue: self = .red
                case Self.blue.rawValue: self = .blue
                default: self = .unknown
            }
        }
    }
    
    opened by DantePuglisi 0
  • Why does non-optional types have optional: true?

    Why does non-optional types have optional: true?

    subtype { type = string; indexed = NO; isPrimary = NO; array = NO; set = NO; dictionary = NO; optional = YES; } type { type = string; indexed = NO; isPrimary = NO; array = NO; set = NO; dictionary = NO; optional = YES; } swx_stag { type = string; indexed = NO; isPrimary = NO; array = NO; set = NO; dictionary = NO; optional = YES; }

    @arturdev 
    
    opened by abaig-experlabs 5
  • Bool can't add to realm

    Bool can't add to realm

    When Bool default value is 'true', can't save to realm I changed the demo

    struct ToDoItem: Realmable {
        var id = UUID().uuidString
        var text = ""
        var isCompleted = true //modified this default value
        
        static func primaryKey() -> String? {
            return "id"
        }
    }
    

    when I set the 'isCompleted' default value is true. can't save the false to the realm

    opened by IAFung 4
  • How to update only some properties of record?

    How to update only some properties of record?

    How can I update only some properties with keeping old other properties? Seems like Realm.create(_ : value: update) is not implemented. Thanks for this awesome repo.

    opened by NortromInsanlyDev 4
  • Properties don't save to realm

    Properties don't save to realm

    Hi just found this and it's so nice to have the ability to use swift types instead of realm types! Keep up the good job!

    I have a question about some types of properties that i'm not sure if they are supported or not but i saw one of them in your User object example so i thought maybe they would be. When I init the struct and print it out, I can see all those values. After i save them into realm and retrieve them the optional dictionary and array of enum shows up nil but the array of enum and dictionary that was inited to an empty value displays the correct value.

    Optional Array of Enum Optional Dictionary of String: String Optional Enum = Crashes on build

    Are those types above supported an i'm doing something wrong or are they not supported?

    This is the testing struct I'm testing with: Screen Shot 2021-01-13 at 11 23 28 AM

    The Init: Screen Shot 2021-01-13 at 11 23 37 AM

    opened by Ludicrous2k 0
Releases(1.9.4)
Owner
Artur Mkrtchyan
Senior Software Engineer at TeamViewer
Artur  Mkrtchyan
Enables developers to write code that interacts with CloudKit in targets that don't support the CloudKit Framework directly

CloudKit Web Services This package enables developers to write code that interac

Eric Dorphy 2 Dec 27, 2021
CoreData/Realm sweet wrapper written in Swift

What is SugarRecord? SugarRecord is a persistence wrapper designed to make working with persistence solutions like CoreData in a much easier way. Than

Modo 2.1k Dec 9, 2022
Realm is a mobile database: a replacement for Core Data & SQLite

Realm is a mobile database that runs directly inside phones, tablets or wearables. This repository holds the source code for the iOS, macOS, tvOS & wa

Realm 15.7k Jan 1, 2023
A library that provides the ability to import/export Realm files from a variety of data container formats.

Realm Converter Realm Converter is an open source software utility framework to make it easier to get data both in and out of Realm. It has been built

Realm 212 Dec 9, 2022
Sync Realm Database with CloudKit

IceCream helps you sync Realm Database with CloudKit. It works like magic! Features Realm Database Off-line First Thread Safety Reactive Programming O

Soledad 1.8k Jan 6, 2023
Realm GeoQueries made easy

RealmGeoQueries simplifies spatial queries with Realm Cocoa. In the absence of and official functions, this library provide the possibility to do prox

Marc Hervera 142 Jul 21, 2022
A simple order manager, created in order to try Realm database

Overview A simple order manager, created in order to get acquainted with the features and limitations of the local Realm database. The project is writ

Kirill Sidorov 0 Oct 14, 2021
Creating a Todo app using Realm and SwiftUI

Realmで作るTodoアプリ note記事「【SwiftUI】Realmを使ってTodoアプリを作る」のソースです。

null 1 Jul 20, 2022
MagicData - A replacement of SQlite, CoreData or Realm.

MagicData A replacement of SQlite, CoreData or Realm. It is very easy to use and is a light version. Guides MagicData We use MagicData manage all the

Underthestars-zhy 20 Jul 4, 2022
Realm-powered Core Data persistent store

RealmIncrementalStore Realm-powered Core Data persistent store Wait, what? I like Realm. Realm's memory-mapped DB blows other databases out of the wat

Eureka 227 Jun 24, 2022
Realm Manager for iOS

Microservices for RealmSwift. Split realms for easier management and migration

Lê Xuân Quỳnh 2 Aug 13, 2022
Typed key-value storage solution to store Codable types in various persistence layers with few lines of code!

?? Stores A typed key-value storage solution to store Codable types in various persistence layers like User Defaults, File System, Core Data, Keychain

Omar Albeik 94 Dec 31, 2022
SwiftPlus - A Swift extension.

SwiftPlus SwiftPlus is made to have a package which contains everyday use extensions, functions and helper classes. Documentation You can find the doc

Knoggl 1 Apr 1, 2022
'Droid Inventor Kit' extension library.

DroidKit Description - Do you know 'Droid Inventor Kit' ? (Quote: ‘TURN EVERYONE INTO AN INVENTOR’: THE STORY OF THE LITTLEBITS DROID INVENTOR KIT) 'D

hcrane 16 Dec 30, 2022
Shows the issue with swift using an ObjC class which has a property from a swift package.

SwiftObjCSwiftTest Shows the issue with swift using an ObjC class which has a property from a swift package. The Swift class (created as @objc derived

Scott Little 0 Nov 8, 2021
🔥 🔥 🔥Support for ORM operation,Customize the PQL syntax for quick queries,Support dynamic query,Secure thread protection mechanism,Support native operation,Support for XML configuration operations,Support compression, backup, porting MySQL, SQL Server operation,Support transaction operations.

?? ?? ??Support for ORM operation,Customize the PQL syntax for quick queries,Support dynamic query,Secure thread protection mechanism,Support native operation,Support for XML configuration operations,Support compression, backup, porting MySQL, SQL Server operation,Support transaction operations.

null 60 Dec 12, 2022
Native iOS app for Habitica

Habitica for iOS Native iOS app for Habitica. Contributing For an introduction to the technologies used and how the software is organized, refer to Co

HabitRPG 440 Dec 22, 2022
The BART app for commuters, now native on iOS

Arrival iOS Built with SwiftUI, Arrival is the BART app for commuters. Available for download on the App Store: https://apps.apple.com/us/app/arrival-

Ronan 7 Aug 5, 2022