Using Realm Swift with initializers throws constant errors - ios

Xcode 7.1 and Swift 2.1 with latest Realm Swift 0.96.2
I created a model class for Realm but it is constantly throwing errors about inits. I understand initializers to an extent for subclasses but I can't wrap my head around this and why it fails. Here's the class I made:
import UIKit
import RealmSwift
class Boxes: Object {
dynamic var precessor: String = "B";
dynamic var id: Int = 0;
dynamic var boxNumber: String {
return "\(precessor) \(id)"; //computed property
}
dynamic var boxDescription: String? = "";
dynamic var brand: String? = "";
dynamic let dateCreated: NSDate
dynamic var dateUpdated: NSDate?
dynamic var photo: UIImage?
dynamic var tags: NSArray? = [];
override static func primaryKey() -> String? {
return "id"; //sets primary key of the model
}
init(precessor: String, id: Int, description: String, brand: String, dateCreated: NSDate, dateUpdated: NSDate) {
self.precessor = precessor;
self.boxDescription = description;
self.brand = brand;
self.dateUpdated = dateUpdated;
self.dateCreated = dateCreated;
super.init();
}
}
This won't build when I try and it tells me:
'required' initializer 'init()' must be provided by subclass of 'Object'
And that I need this line added:
required init() {
fatalError("init() has not been implemented")
}
That satiates the compiler enough to let me build the project. However when I run the project, it always errors out and give me the fatalError line in the output. I know it's doing this as a last resort initializer but I can't figure out why.
Is this related to a super initializer I'm missing somewhere? I'm relatively new to swift but I can get my initializers to work if I don't subclass my class with Object

You are required to implement init() but Xcode doesn't know how to implement if for you so it puts in fatalError("init() has not been implemented") to remind you to implement it.
You probably just want to call super. So:
required init() {
super.init()
}

Related

Issue with adding Data to an AnyObject Var so that I could make native ads work

for postdata in postdata {
if index < tableViewItems.count {
tableViewItems.insert(postdata, at: index)
index += adInterval
} else {
break
}
}
I'll need to add both PostData ads and Native Ads on the same AnyObject Var for me to get it to work and I can't find a way to add the Post Data because it says an error appears saying "Argument type 'PostData' expected to be an instance of a class or class-constrained type." Assistance would be very much appreciated, thank you.
edit 1
class Ad {
var postimage: String!
var publisher: String!
var timestring: String!
var timestamp = Date().timeIntervalSince1970
}
class PostDataAd: Ad {
// Declare here your custom properties
struct PostData1
{
var postimage: String
var publisher: String
var timestring : String
var timestamp = Date().timeIntervalSince1970
}
}
class NativeAd: Ad {
// Declare here your custom properties
struct NativeAd
{
var nativeAds: [GADUnifiedNativeAd] = [GADUnifiedNativeAd]()
}
}
My model class to merge both Data into one AnyObject Var
and then trying to append the Data from Firebase by doing this
var ads: [Ad] = [PostDataAd(), NativeAd()]
let postList = PostDataAd.PostData1(postimage: postimage, publisher:
postpublisher, timestring: postid, timestamp: timestamp)
self.ads.insert(postList, at:0)
an error occurs saying Cannot convert value of type 'PostDataAd.PostData1' to expected argument type 'Ad'
I hope I got what you want correctly. So basically you have two objects which you want to store in one array, under AnyObject. If that is correct, I recommend you to go in a bit of different direction. It is a nice example where you can use subclassing. You can declare a class called Ad, where you define the common properties which will be true for both PostDataAds and NativeAds.
class Ad {
// Add here the common elements you want to retrieve from both classes
var name: String = ""
}
After you define your PostDataAds and NativeAds inheriting from Ad:
class PostDataAd: Ad {
// Declare here your custom properties
}
class NativeAd: Ad {
// Declare here your custom properties
}
And if you want to define an array with two types of objects you can go:
let ads: [Ad] = [PostDataAd(), NativeAd()]
When retrieving you can check their type:
if let item = ads.first as? PostDataAd {
// The Ad is a PostDataAd
} else if let item = ad as? NativeAd {
// The Ad is a NativeAd
}
Or at some cases you don't even how to know the exact type, as you can access the properties defined in Ad without checking.
Update:
First of all your PostData1 and Ad objects are the same, you don't need to duplicate them. If you really want to have two classes you can inherit PostData1 from Ad.
class Ad {
var postimage: String
var publisher: String
var timestring: String
var timestamp = Date().timeIntervalSince1970
// You can add timestamp here also if you wish
init(postimage: String, publisher: String, timestring: String) {
self.postimage = postimage
self.publisher = publisher
self.timestring = timestring
}
}
class PostDataAd: Ad {
// Define some custom properties
}
And if you want to append PostData to the [Ad] array, you would do the following:
var ads: [Ad] = []
// Replace with your values
let postList = PostDataAd(postimage: "", publisher: "", timestring: "")
ads.insert(postList, at: 0)
// Appending NativeAd works also
let nativeAdd = NativeAd(postimage: "", publisher: "", timestring: "")
ads.append(nativeAdd)

Why does adding a convenience init to a Realm object declaration mess with private values?

I have created a Realm object that needs to store an enum value. To do that I use a method outlined in this question which involves declaring a private property of type String, and then declaring another property of type Enum that sets/reads the private property using getters and setters.
For ease of reference here is the code for that:
#objcMembers
class PlaylistRealmObject: Object {
dynamic var id: String = UUID().uuidString
dynamic var created: Date = Date()
dynamic var title: String = ""
private dynamic var revisionTypeRaw: String = RevisionType.noReminder.rawValue
var revisionType: RevisionType {
get { return RevisionType(rawValue: revisionTypeRaw)! }
set { revisionTypeRaw = newValue.rawValue }
}
let reminders = List<ReminderRealmObject>()
let cardsInPlaylist = List<CardRealmObject>()
override static func primaryKey() -> String? {
return "id"
}
}
I have noticed though that if I add a convenience init to the class declaration (to make it a bit easier to initialise the object) the revisionType properties on the objects I end up with adopt the default value declared in the class, and NOT the revision type value passed to the class using the convenience init.
Here is the class declaration with a convenience init
#objcMembers
class PlaylistRealmObject: Object {
dynamic var id: String = UUID().uuidString
dynamic var created: Date = Date()
dynamic var title: String = ""
private dynamic var revisionTypeRaw: String = RevisionType.noReminder.rawValue
var revisionType: RevisionType {
get { return RevisionType(rawValue: revisionTypeRaw)! }
set { revisionTypeRaw = newValue.rawValue }
}
let reminders = List<ReminderRealmObject>()
let cardsInPlaylist = List<CardRealmObject>()
convenience init(title: String, revisionType: RevisionType) {
self.init()
self.title = title
self.revisionType = revisionType
}
override static func primaryKey() -> String? {
return "id"
}
}
And - to make things even more perplexing - if I simply remove the word 'private' from the revisionTypeRaw property, everything works fine!
I am confused. 1) Why does adding a convenience init have this effect? 2) Why does making the property 'public' resolve the issue?
I have created a demo Xcode project to illustrate the issue and can share it if anyone needs it.
Update:
I found the problem. It has nothing to do with the convenience init. I am using #objcMembers at the top of the class as per the Realm docs: https://realm.io/docs/swift/latest/#property-attributes
If you remove this and place #objc in front of the private keyword, everything works as would be expected. I guess the question then is: what explains this behaviour?
This is a good question but I think the issue is elsewhere in the code. Let's test it.
I created a TestClass that has a Realm managed publicly visible var, name, as well as a non-managed public var visibleVar which is backed by a Realm managed private var, privateVar. I also included a convenience init per the question. The important part is the privateVar is being set to the string "placeholder" so we need to see if that is overwritten.
class TestClass: Object {
#objc dynamic var name = ""
#objc private dynamic var privateVar = "placeholder"
var visibleVar: String {
get {
return self.privateVar
}
set {
self.privateVar = newValue
}
}
convenience init(aName: String, aString: String) {
self.init()
self.name = aName
self.visibleVar = aString
}
}
We then create two instances and save them in Realm
let a = TestClass(aName: "some name", aString: "some string")
let b = TestClass(aName: "another name", aString: "another string")
realm.add(a)
realm.add(b)
Then a button action to load the two objects from Realm and print them.
let testResults = realm.objects(TestClass.self)
for test in testResults {
print(test.name, test.visibleVar)
}
and the output:
some name some string
another name another string
So in this case, the default value of "placeholder" is being overwritten correctly when the instances are being created.
Edit:
A bit more info.
By defining your entire class with #objMembers, it exposes your propertites to Objective-C, but then private hides them again. So that property is not exposed to ObjC. To reverse that hiding, you have to say #objc explicitly. So, better practice is to define the managed Realm properties per line with #objc dynamic.

Realm Swift - save a reference to another object

I thought this would be pretty straightforward after reading here and here but I'm a bit stuck.
I have a 'favouriteWorkout' object that looks like this :
class FavouriteObject: Object {
#objc dynamic var favouriteWorkoutName = ""
#objc dynamic var workoutReference = WorkoutSessionObject()
override class func primaryKey() -> String? {
return "favouriteWorkoutName"
}
}
What I'm trying to do here is reference a WorkoutSessionObject in Realm that links from a WorkoutName when a workout is saved as a favourite.
My WorkoutSessionObject has a primary key of workoutID which is a UUID string. It looks like this :
class WorkoutSessionObject: Object {
#objc dynamic var workoutID = UUID().uuidString
#objc dynamic var workoutType = ""
let exercises = List<WorkoutExercise>()
#objc dynamic var totalExerciseCount = 0
#objc dynamic var rounds = 0
#objc dynamic var favourite : Bool = false
override class func primaryKey() -> String? {
return "workoutID"
}
}
I've then tried to save using this :
let favouriteWorkout = FavouriteObject()
favouriteWorkout.favouriteWorkoutName = favouriteName
favouriteWorkout.workoutReference = (realm.object(ofType: WorkoutSessionObject.self, forPrimaryKey: self.workoutID))!
do {
try realm.write {
realm.add(favouriteWorkout)
}
} catch {
print ("Error adding favourite")
}
but i get a crash when I run of :
'RLMException', reason: 'The FavouriteObject.workoutReference property must be marked as being optional.
However, when I then try to make it optional (by adding ?) it says
"Cannot use optional chaining on non-optional value of type 'WorkoutSessionObject"!
Summary
I want to save a reference of the workoutID of a WorkoutSessionObject in my FavouriteObject which is an actual link to the WorkoutSessionObject (so the properties can be accessed from favourites)
Update
using the answers below I've now sorted the problem of the workout reference. This is now showing in Realm as the proper format () under "workoutReference". However, I'm now getting "nil" in "workoutReference" when trying to save. I know the workoutID is coming through correctly as I am printing it in the console.
You need to change the declaration of workoutReference. First of all, you need to make it Optional by writing ? after the type. Secondly, you shouldn't assign a default value to it, it needs to be Optional for a reason. The linked docs clearly state that
to-one relationships must be optional
, and workoutReference is clearly a to-one relationship.
class FavouriteObject: Object {
#objc dynamic var favouriteWorkoutName = ""
#objc dynamic var workoutReference:WorkoutSessionObject?
override class func primaryKey() -> String? {
return "favouriteWorkoutName"
}
}
In property-cheatsheet you can see that a non-optional Object-property is not allowed, so you have to change it like the following:
class FavouriteObject: Object {
#objc dynamic var favouriteWorkoutName = ""
// here you have to make the property optional
#objc dynamic var workoutReference: WorkoutSessionObject?
override class func primaryKey() -> String? {
return "favouriteWorkoutName"
}
}

Is there a way to create a custom class that I can mutate?

Currently, I've made a custom class called SongNames. Here's the code for it:
import Foundation
class songAttributes {
private var _songTitle: String!
private var _songURL: String!
var songTitle: String {
return _songTitle
}
init(songTitle: String, songURL: String) {
_songURL = songURL
_songTitle = songTitle
}
var songURL: String {
return _songURL
}
}
I have no problem setting values for this class. For instance, I might write:
var songAttribute = songAttributes(songTitle: "That's What I Like", url: "some url")
However, if I try to change the properties of my variable that I just created, like saying:
songAttribute.songTitle = "Locked Out of Heaven"
I get the message: "error: songTitle is a get only property"
That being said, is there a way to mess with my SongName class so that these properties can be changed, and not just get-only?
If you want the properties to be settable then there is no need for the dance with the private properties. Also, the properties should not be implicitly unwrapped, since you are setting them in the initialiser.
import Foundation
class SongAttributes {
var songTitle: String
var songURL: String
init(songTitle: String, songURL: String) {
self.songURL = songURL
self.songTitle = songTitle
}
}
Note that, by convention, class and struct names should start with a capital letter.
You are doing a lot of unnecessary work. You have private variables backing all of your public variables, and have made your public variables computed properties. Get rid of all that. It's needless complexity:
import Foundation
class songAttributes {
var songTitle: String
var songURL: String
init(songTitle: String, songURL: String) {
self.songURL = songURL
self.songTitle = songTitle
}
}
By default properties are read/write, so you don't need to do anything special.
The pattern of having private backing variables that start with the _ prefix is largely a holdover from Objective-C, and rarely needed in Swift.

RealmSwift initializers - Xcode fix-it keeps getting it wrong

I cannot get Realm working when I want to provide initializer for a class, Xcode endlessly suggest errors.
I decided to upload two screenshots instead of code snippet to make it easier to see errors
I follow the suggestions and end up with this
The last error tells "Use of undeclared type 'RLMObjectSchema'
I use the latest 0.99 version of RealmSwift
The recommended way is creating memberwise convenience initializer, like the following:
class Item: Object {
dynamic var isBook: Bool = true
dynamic var numberOfPages: Double = 0
dynamic var isInForeignLanguage: Bool = true
dynamic var isFictional: Bool = true
dynamic var value: Int {
get {
return calculalatedValue()
}
}
convenience init(isBook: Bool, numberOfPages: Double, isInForeignLanguage: Bool, isFictional: Bool) {
self.init()
self.isBook = isBook
self.numberOfPages = numberOfPages
self.isInForeignLanguage = isInForeignLanguage
self.isFictional = isFictional
}
...
}
You cannot omit default initializer because Realm needs default initializer for instantiating objects for querying. When querying to the Realm, Realm calls default initializer internally to instantiate the objects.
You can also override default initializer, but we don't recommend it. Because when you override the default initializer, you should override other required initializers inherited from ObjC layer due to Swift type system limitation. Also you should import both Realm and RealmSwift frameworks. Because there are Objective-C only class in the parameters of those initializers.
import RealmSwift
import Realm // Need to add import if you override default initializer!
class Item: Object {
dynamic var isBook: Bool = true
dynamic var numberOfPages: Double = 0
dynamic var isInForeignLanguage: Bool = true
dynamic var isFictional: Bool = true
dynamic var value: Int {
get {
return calculalatedValue()
}
}
required init() {
super.init()
}
required init(realm: RLMRealm, schema: RLMObjectSchema) {
super.init(realm: realm, schema: schema)
}
required init(value: AnyObject, schema: RLMSchema) {
super.init(value: value, schema: schema)
}
Try:
required convenience init(...) {
self.init()
...
}
See https://github.com/realm/realm-cocoa/issues/1849

Resources