Model classes — what the heck do they really mean?

2019-04-10 17:41发布

I really can't seem to get the hang of Model objects in MVC. I wonder why we can't just work with arrays and dictionaries and arrays OF dictionaries?

I understand that they represent the 'data' that my other classes manipulate and work with. But what is the proper way they should be constructed? Suppose I've got a plist I want to read and display in a table view. I could just load it directly into an array property in my viewDidLoad method and then use it, right? Why would I want to use a Model class, and how would I go about constructing it?

In addition, any links to resources/blogs out there that explain this point would be greatly appreciated!

1条回答
Deceive 欺骗
2楼-- · 2019-04-10 18:42

You absolutely can work with dictionaries and arrays -- there's nothing wrong with using those as part of (or all of) your data model. Core Data's NSManagedObject is very much like a dictionary. But sometimes you want your model objects to do more than just store data -- you might also want them to know something about how the various bits of data relate to each other, operate on the data, and so forth.

Consider how you'd represent a Person in your data model. Could be a dictionary, right? With keys like firstName, lastName, middleName, address, phone, email, dateOfBirth... If you use a plain old dictionary, mutable or not, you just store the appropriate value for each key and you're done. If that's really all you need, you're done.

On the other hand, you can derive a lot of other information from those fields without needing to store extra data. If you create a custom Person class, you can give it keys like fullName, age, initials, monogram, and vCard. The custom class could have methods for each of those that manipulate the stored information to come up with the appropriate values. Example:

- (NSString*)fullName
{
    return [NSString stringWithFormat:@"%@ %@ %@", self.firstName, self.middleName, self.lastName];
}

That's just a very simple example. Maybe your app manages the entire inventory of a group of warehouses. In that case, you'd probably want classes representing part, bin, palette, location, supplier, destination, order, invoice, forklift, operator, etc. When someone picks a part from a bin, you'd want that bin to know how many parts are left and send a notification if the number is smaller than some threshold. That notification might trigger an event that tells a forklift to go get another palette of that kind of part and deliver it to the bin. Once picked, the part should be transferred from the bin to an order. The order, of course, should know how to generate an appropriate invoice. And so on. All this logic can be part of the model.

查看更多
登录 后发表回答