Circular Reference between 2 classes - swift

I have a problem trying to solve this circular reference.
First I have two NSManagedObject ACoreData and BCoreData
I want to separate the model from the DataBase layer to the UI Model.
So, I create A and B classes which those will be in the UI.
I have created a protocol (Convertible) that ACoreData and BCoreData will implement to convert to the ui objects.
So far so good, but now I have a problem. Each time I call convert from ACoreData it will create a new A and it will assign the BCoreData converted, but then the BCoreData object will call convert again for the A object. I will end up with a loop calling convert() each other.
This is the code:
protocol Convertible{
associatedtype T
func convert() -> T
}
class ACoreData: Convertible{
var b: BCoreData?
func convert() -> A {
var a = A()
a.b = self.b?.convert()
return a
}
}
class BCoreData: Convertible{
var a: ACoreData?
func convert() -> B {
var b = B()
b.a = self.a?.convert()
return b
}
}
class A{
var b: B?
}
class B{
var a: A?
}
Do you know how can I solve this problem to avoid the loop in this circle reference?
Thanks in advance.

I suggest that the best solution is don't do this. You're adding a lot of complexity to your code for no real advantage. Weigh the benefits you see for keeping managed objects away from the UI against the additional complexity of needing to convert to/from managed objects all the time, copying values from one to the other any time one of them changes, the memory hit of keeping duplicate copies of data around, and probably other stuff I haven't thought of yet. "Clean" architecture is going to cost you a lot in terms of maintainability and performance.
If you don't want the UI to know about managed objects, define a protocol that your managed objects adopt. Make the UI work with "things that implement the protocol" instead of managed objects. Keeping the UI unaware of the details of the data store does not require duplicate data models.

Related

Hiding property setters by class in Swift

I would like to hide some property setters and initializers on my Swift model objects. These are reference data that the server provides, and under no circumstances should they be created or modified by the application. This is simple enough in Swift.
However, there is application in my project (a separate target) that needs to break this rule. It is a tool I use to populate the data in bulk, so of course needs to be able to initialize new model objects and set their properties.
What are my options for accomplishing this? I would rather not use a completely new project since it will mean a lot of code duplication. Is there some language-level way to keep this mutability hidden from one application but available to another?
If you declare a property with the let keyword. It can then only be set in the init of the type.
You can also declare a private setter to make the property readonly from the caller of the type but read/write inside the type
struct Foo {
private(set) var bar: Bool = true
func toggle() {
bar.toggle()
}
}
var foo = Foo()
let barState = foo.bar // This works
foo.toggle() // This works too
foo.bar.toggle() // This will make a compile time error

Making a shared class in swift

In swift, is there anyway I can create a shared class? That is, say there is a class called Value:
class Value{
var a = 0
}
I want to use this class to be shared among different object instances.
For example,
class Main{
func main(){
print(Value.a)
Value.a++
}
}
class OtherClass{
func otherMain(){
print(Value.a)
Value.a++
}
}
let main = Main()
let other = OtherClass()
//I want this call to print 0
main.main()
//I want this call to print 1
other.otherMain()
I tried static on var a, but then it won't let me do arithmetics such as addition... But it is working if I change the Value into static instead of class. I thought only difference between struct and class was either variable type or reference type...
I'll appreciate to any help. Thanks
The best way to go about what you want to do, unfortunately, is not to do it at all. It seems that the architecture you're designing is quite fragile and two independent classes shouldn't depend on a shared object state and if they do, they should be related via class inheritance or protocols.
A better solution would be:
class MyClass {
static var a = 0
}
class SubclassA: MyClass {
func someFunc() {
print(self.dynamicType.a)
self.dynamicType.a += 1
}
}
class SubclassB: MyClass {
func otherFunc() {
print(self.dynamicType.a)
}
}
There's a few reasons you should do it this way, over your previous solution:
Your shared state can stay private to those two classes. No one outside of those classes can or should modify that value.
Singleton patterns while sometimes useful, have a bunch of problems. This article explains it better than I can.
You have to think of your application and your code architecture as a state machine, moving from one state to another. The goal is to write code that's reusable, modular, generic, and has as little state as possible. The more stateless your code, the better. That's the whole idea behind platforms like ReactJS and ReactiveCocoa; they help simplify that application state.
What you might be looking for is data persistence, something like Realm or CoreData, where you persist data to disk and then you can read it back at a later time as needed. Imagine for example that instead of an Int your shared state was an array of UIImages. With the singleton pattern, you're keeping those images in memory at all times. What if the list grows to be 200 or 300 in length? Then you have memory issues.

Best practice for array as property in Swift

I have a model class in Swift, whose primary purpose is to contain an array of custom objects, but also has other methods/properties etc.
public class Budget: NSObject, NSCoding {
var lineItems : [LineItem] = []
// Other methods
// Other properties
}
As I understand it, it's best practice to not make the property publicly settable, but I want it to be testable, so lineItems needs to be publicly gettable.
Reading the docs, I could do this:
private(set) public var lineItems : [LineItem] = []
But then I have to write a lot of boilerplate code to recreate array methods, such as insert, removeAtIndex etc.
What is best practice here? At the moment, I don't need to do anything else on insert/removal of items, but I guess I may need to do validation or similar in future, but even so it seems redundant to have to write code that just recreates Array methods.
Would it be better just to make lineItems publicly gettable and settable? Are their circumstances where this would or wouldn't make sense?
Thanks!
Swift's Array is a (immutable) value type, which means that
var a = ["object"]
var b = [String]()
b.append("object")
b == a // true
From this point of view it does not make sense to allow modifying an array and not allow setting it - modifying is basically creating new array and assigning it to variable.

Different types of the same object

So, I'm in Xcode and programming a small program from a friend.
I want to initialize several instances of an object, put them in an array and then iterate through it (via a function that returns a string). Each object adds some text to that string when it's iterated, depending on the variables of the object.
Let's say the class is Tree. The variables in the class are name (string), height(int) and a hasLeaves(bool)(weather it currently has leaves on it or not). I could easily print:
"This is a name that is height meters tall and has leaves.
The problem is that I want the string to be a bit different, depending on which kind of tree it is. Like this:
The oak(name) is big and lifeful, it's height meters tall and has leaves.
Apple trees(name) carries some apples, it's height meters tall and has leaves.
If you ever visit Sweden you should check out the firs(name), they are height tall and haven't got leaves.
I don't want you to write the code for me, but give me a clue. I don't know what to look for. I was thinking about creating a subclass for each Tree, but every subclass would only appear once in the program and I don't know if it's necessary or not.
As you recognize, I'm having a hard time even formulating this question, but if you understand my intentions I'm glad for any clue I can get.
Edit: So this is my attempt to show it in code:
Class:
class tree {
var treeHeight: Int?
var treeWidth: Int?
var hasLeaves: Bool
var treeString: String
init (height: Int?, width: Int?, leaves: Bool, theString: String) {
self.treeHeight = height
self.treeWidth = width
self.hasLeaves = leaves
self.treeString = theString
}
}
Main function:
var oak: tree = tree(height: 1, width: 2, leaves: true, theString:"Oh, the mighty oak")
var appleTree: tree = tree(height: 1, width: 2, leaves: false, theString: "Yummy Apples")
var treeArray: Array = [oak, appleTree]
var resultString = "This is the stories of the trees: "
for tree in treeArray {
if tree.hasLeaves == true {
resultString = resultString + tree.theString
}
}
So, I want the string added to the "resultString" to be different, depending on what kind of tree it is, but I don't want to set that string in the initialization of the object, but rather from what "kind" of tree it is. Does that make it easier to understand?
I want the string (treeString) to be static depending on what "kind" of tree it is. So if it is an oak, the string is always "Oh, the might oak".
It sounds like you want a tree class with some properties like leaves, etc. Maybe you also want to subclass leaves with additional properties like color, etc. I recommend the WWDC 2014 video:
http://youtu.be/W1s9ZjDkSN0
Somewhere around 30 minutes they have a demo of a Car class with RaceCar at subclass.
Regarding creating the objects, you can build each object individually and then collect them in an array as one option. For example, maybe in a form on your app the user inputs data for a class or subclass and then you create an object, store to a master array which you then archive to a file.
So, if anyone stumbles in to this question, this is what I learned:
I was looking for subclasses and protocols. There are methods to determining whether an object is of a certain subclass, and in my case, I could have a protocol called "Tree" with certain methods and/or methods, and then make subclasses to this protocol, called "oak" and "fir".

enum-like data structuring or alternatives

I have a design issue which has proven to bee too much for my current design skills.
I hope my request is not too trivial or too stupid for the incredibly skilled people I saw in these forums over time.
Basically, this is what I need:
to be able to reference a specific class instantiation by means of another class static or constant declaration (hope it makes as much sense to you as it does to me, hah).
The 'enum' behavior would be particularly useful for its 'ease of access' and for its standard methods.
//simple class with a constructor
public class myclass {
int myint = 0;
string mystring = "";
public myclass(int localint, string localstring) {
myint = localint;
mystring = localstring;
}
}
//the core of the issue.
public enum myenum : myclass {
enum1 = new myclass(9,"abr"),
enum2 = new myclass(99,"acad"),
enum3 = new myclass(999,"abra")
}
So that elsewhere, when I need 'abra', instead of manually instantiating it, and having countless duplicates all over the code, I just
myenum mylocalenum;
mylocalenum = enum3; //no mistake, the underlying class variables are predefined
The purpose is to have a selectable, pre-set 'myenum' which basically encapsulates another data structure which I predefine in the declaration phase.
This is because I have several data pre-sets by design, and I need to interact with them as with an enum (get their number, their descriptions, and basically associate them with predefined values).
If you have a solution, or even a resembling alternative, please let me know.