0

I have a Tableviewcontroller BeamsNameVC with 2 variables: Name and number. If for example, the number is 7, and if I click on any row in this View controller, it will segue to another TableViewcontroller SpansListVC and than it will show 7 rows: S1, S2, S3, S4, S5, S6 & S7.

I want to save these Data, so I created 2 swift files:

class StructureElement: NSObject, NSCoding {

var name = ""
var nbrSpans = ""
var spans = [LoadDetailsForEachSpan]()

and

class LoadDetailsForEachSpan: NSObject, NSCoding {

var i_SpanName = ""
var i_Spanlength = ""
var i_ConcentratedLoadForEachSpans = [ConcentratedLoadForEachSpan]()

I created a protocol with the following:

let spanNbr = Int(structureElement[newRowIndex].nbrSpans)
let newElementDetailSpan = LoadDetailsForEachSpan()
    for i in 0...spanNbr! {
        newElementDetailSpan.i_SpanName = "S" + " \(i)"
        structureElement[newRowIndex].spans.append(newElementDetailSpan)
    }

If i run the application, it will segue to * SpansListVC* but all values are the last i.

Example:

if name is Test 7 and number of span is 7, I will be having inside *[Spans] * 7 values with the same name:

spans[0] = S 7  
spans[1] = S 7  
....

Any mistake with above code?

0

2 Answers 2

1

Welcome to the hell that mutable data objects can be ;). You are creating a single LoadDetailsForEachSpan instance and add that same instance a number of times to the array, while setting the i_SpanName property of that same instance every time the loop is iterated. You probably want to pull the instance creation into the loop:

for i in 0...spanNbr! {
    let newElementDetailSpan = LoadDetailsForEachSpan()
    newElementDetailSpan.i_SpanName = "S" + " \(i)"
    structureElement[newRowIndex].spans.append(newElementDetailSpan)
}
Sign up to request clarification or add additional context in comments.

Comments

0

Thanks @thm for your reply.

however, i find another solution as follow and it works:

    var spanDetailAndLoadItem: [SpanDetailsAndLoads] = []

    for var i in 1...nbr! {
        let item = SpanDetailsAndLoads(name: "S\(i) - S\(i + 1)")
        spanDetailAndLoadItem.append(item)
    }
    self.spans = spanDetailAndLoadItem

2 Comments

The actual solution is exactly what I said: pull the creation into the loop. Your answer is also mostly disconnected from your question: SpanDetailsAndLoads is not in there. Neither is init(name:), nor is nbr.
I modified the code in a way to have it works and to save it too. however I will put yours as the correct question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.