简体   繁体   中英

Why does value of object change in Array when trying to append?

I have a custom class "Book" and I am trying to save two books in an array in the following way:

class ViewController: UIViewController, UITableViewDataSource, 
{

            testBook.setBookTitle(title: "Harry Potter")
            testBook.setbookPage(page: 12)

            myBookCollection.append(testBook)

//            testBook = Book()

            testBook.setBookTitle(title: "testing")
            testBook.setbookPage(page: 66)

            myBookCollection.append(testBook)



            for books in myBookCollection
            {
                print(books.getBookTitle())
            }

}

If I run the above I my books in the array are stored as ["testing","testing"] as opposed to ["Harry Potter","testing"].

However If I uncomment testbook = Book() it works fine. Can someone please explain why this is the case ?

thanks,

the array doesn't hold a copy of your Book instance , it simply hold the pointer to the object(book). When you change the title and page you are not changing the array contents, you are changing the object which testbook is pointing to. however if you uncomment the line testBook = Book() . You create a new instance of Book class and you set the pointer testbook to the newly created object and all the changes from this point is done on the new object and that's why it works as it should. And all of this is true if your are using a class in your array , if you use struct that's another story

Reference vs. value type.

If you define Book as a class, when you add it to array, it does not copy our object. testBook and myBookCollection[0] are holding the same object. When you change either one, the other will be affected. If you add testbook = Book() , then testBook is now pointing to a different object in memory and what you do it it has no impact on myBookCollection[0] .

You can change Book from a class (reference type) to a struct (value type). In that case, when you add it to an array, it will add a copy to the array so what you do with testBook after doesn't affect it.

Here's a video from WWDC that demonstrates the exact problem you had: Building Better App with Value Types in Swift

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM