Reputation: 684
Here comes a possibly very simple question. I have created a custom 'Person' class which stores information about a specific person. Below is the following class I have created:
class Person: NSObject {
var name: String
var age: Int
var height: Double
init(name: String, age: Int, height: Double) {
self.name = name
self.age = age
self.height = height
}
}
I can create a new instance of this class like this:
let person1 = Person(name: "Bob", age: 25, height: 1.62)
I also understand that I can store these instances of this class in an array once I've initialised each one. However, the issue is that in my app, I want to have a large number of instances, around 30 of them.
I know the characteristics of each instance of the class that I want before I launch the app.
My question is this. Is there a better way of creating these class instances instead of doing it one-by-one when the app starts?
Upvotes: 0
Views: 626
Reputation: 162712
First, 30 isn't a large number for a simple class. But copy/past'ing 30 copies of the instantiation code would certainly be annoying and the motivation is to split data from code.
To that end, probably the most straightforward is to throw all the data in a simple property list, add the property list to your app as a resource, read it in and then loop on the contents while creating Person() instances along the way.
Allocating and instantiating 30 Person instances is unavoidable, but you can use the above to reduce the # of lines of code necessary to do so.
However, really... 30 lines of:
array.append(Person(...))
Isn't that bad to do once and if you really aren't going to change the data often, why bother with splitting it out? It won't be hard to replace later and, frankly, the best performing program is often the one that ships first.
import Cocoa
class Person: NSObject {
var name: String
var age: Int
var height: Double
init(name: String, age: Int, height: Double) {
self.name = name
self.age = age
self.height = height
}
}
var persons = [Person]()
persons.append(Person(name: "bob", age: 42, height: 6.2))
persons.append(Person(name: "fred", age: 32, height: 5.9))
... repeat 28 times ...
Meh-- for learning? I'd just do the above.
Upvotes: 1
Reputation: 535306
Is there a better way of creating these class instances instead of doing it one-by-one when the app starts?
No. You have to do it just like Superman puts on his pants, one leg at a time. Even your app delegate and your shared application instances have to be created. The only way instances can come about is through instantiation!
However, there might be a better way to code it. For example, you could put the data (i.e. the characteristics of each object) into a .plist file, or an XML file, or even a SQLite database, and load it at launch, rather than writing out every instantiation completely by hand and thus hard-coding those characteristics into your code.
Upvotes: 1