Proper Object Oriented application set up - iphone

I am trying to learn my first programming language. Unfortunately I picked the Iphone to start. Thought it would be easy... ooops. Anyway 4 weeks later I've actually got a couple of working apps! kind of...
One of my apps that had a couple of text boxes and a couple of labels.
Each person has a has button that starts a timer that decrements a label's text for a countdown.
I have 2 separate timers that fire two separate methods that increment variables, play a song, update some labels etc, relative to each person. Not war and piece on the amount of code, but enough not to want to have to change both sets every time I figure out how to do something new.
What is a better way to set this up so that I can work with just one set of code per person? I get the whole "person" as an object idea and that it should be it's own class and that I should be probably sub classing it from all the reading I've done. I just don't know how to practically apply it with actual code.

I think the first place to start is to realize that timers are (almost always) part of the interface and not part of the data model. Unless you have a very strange set of requirements, the timers shouldn't be related to your person data objects at all.
You want to maintain strict seperation between data and the interface. This is the key idea behind the badly misnamed Model-View-Controller pattern. It should be called Model-Controller-View to reflect that the controller mediates between the model and the view.
In your case, it sounds like you have a person object that is your data model. Ideally, that model will work without any direct links to any particular interface. A good data model will work with standard views, a web view or even a text based command line interface. It shouldn't matter to your model because it is only concerned with storing or manipulating data without regard to how it will be displayed or used.
Timers that update the interface belong in the controller because they have nothing to do with the data. The same data displayed in different interfaces would need different timers. You probably only need one timer that simply calls a method in the controller that updates all the interface elements as needed. In that method, the controller then fetches the data it needs to display from the appropriate objects in the data model (Instances of the person class in your case).
For example, suppose you have multiple person objects each with it's own countdown number. You would have the countdown value stored in the person object as a property. A single timer in the controller would fire once per second and call a method in the controller. That method would then ask each person object for its countdown value. Upon being asked for the value, the person object would automatically decrement the countdown value.
With this design, you could handle an arbitrarily large number of person objects, each with its own countdown attribute, with just a single timer and one method in the controller.

We could talk for object oriented design for hours maybe months and years. Design principles exist by they are best learned and mastered through experience and a lot of practice.
If you need 2 timers each one calling 1 method that plays a unique role then you are probably stuck with the 2 timers. If there are common tasks/responsibilities in your two timers you could create an abstract timer that implements these common tasks and extend it for more specific behavior (method implementation).
I have found role based design helpful in many situations, but as i said you will have to practice and of course know the basics of object orientation and inheritance.

Related

Pattern(s) sought for avoiding "action at a distance"

I'm working on a complex and very large web application. Some of the classes within said application require execution of various methods in far-away objects, and I am quickly realizing and stumbling into bugs related to the "action at a distance" antipattern.
Example 1: Some of the classes require execution of daily "cleanup" methods, such as reaper(), cleanup(), send_daily_status_messages(), etc.
Example 2: Some classes mutate the app's state, and require a far-away object to perform a refresh() of its own state.
Example 3: Going back to Example 1, some objects spread throughout the app provide various bits of content to send_daily_status_messages().
To address this, our team has created an Events class that centralizes all of these calls. However we're finding the Events class itself to be a bit too "distant", in the sense that sometimes we make changes in the distributed objects, forget to make changes to the calls within the Events class, and then see bugs.
I'm wondering if there are any better patterns out there?
One thought: For objects to "register" themselves to some sort of dynamic Events class upon initialization. That would keep the invocation code near each object. Objects could maybe even also create different Events?
Lastly, this is for a Perl-based web application that using Moose. So any Perl-specific Moose-friendly recommendations, including CPAN recommendations, would be most appreciated!
The common pattern that sounds like what you're talking about is event dispatch. You can find many different takes on this pattern on CPAN, such as: Event::Distributor, Beam::Emitter, Mixin::Event::Dispatch, Mojo::EventEmitter (which I've extracted to a role). You have some object which is either an event dispatcher or has an event dispatching role applied to it, and everything can subscribe to events, and when something emits an event all of the subscribers get their callback called.

GKEntity/Component update cycle best practices

The subject
My question is about the division of the update cycle when combining Apple's frameworks in order to respect the typical patterns and good practices on the subject, since most of the documentation and example code has not been adapted to Swift yet (or at least I can't find it anywhere).
There are so many ways to manage the update cycles in GameplayKit that I'm not too sure what is a good way of combining everything.
The elements
First and foremost: every class (GKComponent and GKEntity (sub)classes) in the Entity/Component has an update() method that you can override to perform per-frame updates. That has to come from the update cycle of the current GKScene/SKScene.
Then you have the GKComponentSystem that you can use to fire up the update() methods of every component from a given type that has been added to it. I see the point, it's very handy.
But I also want to use the state machine system and it also has an update cycle of it's own... Combining all that got me confused.
My situation
In the case where I have a subclass of GKEntity with an instance of a GKStateMachine created on initialization. The state machine has a few states (for the moment: 'Spawn', 'Normal', 'Stunned' and 'Death'.
Right now, I'm creating a big "cookie cutter" with my GKEntity subclasses and create all the components it's gonna use during the initialization. But it's becoming very impractical. For instance, I have a MovementComponent, which is a subclass of GKAgent2D. I created a singleton that manages entity creation, so after the instance is created, if loops through all the entity's components and add them to the related GKComponentSystems. The singleton has an update() method of it's own that updates passes the call to the GKComponentSystems. Some of the components I use do not need per-frame update, so no GKComponentSystem has been created for them and I update them manually as required.
If I come back to my entity, since I create everything at once and use GKComponentSystems to update the components, my component's update method is loaded with guard and if-let statements because I need to access the entity's state machine, check if it's a state where the entity can move (Normal state) and do its thing or escape the function. This is not efficient in my view: the move component doesn't need to get updated when it's spawning, stunned, or dying.
On top of that it makes my use of GKStateMachine completely overkill since my update methods are empty: the components get updated by the GKComponentSystem anyway.
My ideas
Drop the GKComponentSystems completely and simply loop through all my entities (maybe sort them in different collections at some point if need be) and call their update() methods. Dispatch the updates to the state machine which in turn will update the components involved in that state.
Keep the GKComponentSystems and use the state machine to juggle with the components, for example by adding and removing the MovementComponent from the component systems when entering and exiting the Normal state.
Option 1 is straightforward but could cause problems on the long run when my structure gets more complex becasue some components could need to be updated before others. Having each entity update its own components would scatter the update process.
Option 2 can get confusing too in a way, but my biggest concern is about the creation/removal of the components. Do I only take them out of the GKComponentSystems or do I take them out of the entity completely? What is the most efficient way of doing it?
The actual question
which one of my options would be the best? is there any better way of doing it.
If you are using GKComponentSystem to perform updates, then I would go with just that. I think a component should update only once per frame.
It's not clear from your question what you need to do with StateMachines, but there is no reason to not have them involved either directly in your GKEntity or contained within a GKComponent like the DemoBots IntelligenceComponent.

iOS: using GCD with Core Data

at the heart of it, my app will ask the user for a bunch of numbers, store them via core data, and then my app is responsible for showing the user the average of all these numbers.
So what I figure I should do is that after the user inputs a new number, I could fire up a new thread, fetch all the objects in a NSFetchDescription instance and call it on my NSManagedObjectContext, do the proper calculations, and then update the UI on the main thread.
I'm aware that the rule for concurrency in Core Data is one thread per NSManagedObjectContext instance so what I want to know is, do you I think can what I just described without having my app explode 5 months down the line? I just don't think it's necessary to instantiate a whole a new context just to do some measly calculations...
Based on what you have described, why not just store the numbers as they are entered into a CoreData model and also into an NSMutableArray? It seems as though you are storing these for future retrieval in case someone needs to look at (and maybe modify) a previous calculation. Under that scenario, there is no need to do a fetch after a current set of numbers is entered. Just use a mutable array and populate it with all the numbers for the current calculation. As a number is entered, save it to the model AND to the array. When the user is ready to see the average, do the math on the numbers in the already populated array. If the user wants to modify a previous calculation, retrieve those numbers into an array and work from there.
Bottom line is that you shouldn't need to work with multiple threads and merging Contexts unless you are populating a model from a large data set (like initial seeding of a phonebook, etc). Modifying a Context and calling save on that context is a very fast thing for such a small change as you are describing.
I would say you may want to do some testing, especially in regard to the size of the data set. if it is pretty small, the sqlite calls are pretty fast so you may get away with doing in on the main queue. But if it is going to take some time, then it would be wise to get it off the main thread.
Apple introduced the concept of parent and child managed object contexts in 2011 to make using MO contexts on different threads easier. you may want to check out the WWDC videos on Core Data.
You can use NSExpression with you fetch to get really high performance functions like min, max, average, etc. here is a good link. There are examples on SO
http://useyourloaf.com/blog/2012/01/19/core-data-queries-using-expressions.html
Good luck!

iPhone -- Applying MVC when the view hierarchy has a parallel structure to the model hierarchy

I have a Triangle class. Each Triangle has three edges a, b, and c, and also three angles angleA, angleB, and angleC. In addition to the size (length or angle), each datum also stores whether it was entered by the user or was calculated based on geometric relationships to other data.
Corresponding to my Triangle class, I have a TriangleSidesAndAnglesView. This view has six subviews -- one for each of the angles, and one for each of the sides. The contents of the subviews depends on the information in the model class. The subviews are all of class TriangleDatumView.
Information can pass both ways. For example, if the user enters something in a text field corresponding to an edge or angle, the entered value needs to be passed up to the model.
I am trying to figure out how to keep everything organized. For example, should the TriangleDatumView objects contain references to the respective corresponding members in the model class? Does the TriangleSidesAndAnglesView need to keep a table of which TriangleDatumView corresponds to what model object? Should the TriangleDatumView for (say) edge b know that the name of the edge it is displaying is "b" so that it can write "b=" each time . . . or does it grab that info from the model?
Nothing here is fundamentally difficult. The challenge is organizing it all in a sensible way.
Thanks for any help.
A question I ask myself is "What do I want to be able to independently vary?" -- meaning, if I have a model, could I imagine a totally different implementation of the same interface or a totally different view for the same model. In the variations that I care about, what needs to be where.
So, if labels are always A, B, and C -- I see no reason to store labels in the model. If they can change, then yes, you should not hard-code them in the view.
Views in MVC often have references right to the model they are viewing. Sometimes the controller is an intermediary. Models should usually not contain references to views -- but instead use things like delegates to alert of changes to their state.
I'm in the "Do the simplest thing that works, and don't repeat yourself, refactor when necessary" camp. The issue with building in the complexity at the start is that it might be complex on the wrong axis -- let the features dictate how the interfaces grow.
A view controller could sit between model and view, managing an array of TriangleView instances. The controller adds, modifies and deletes views based on what is in the model, and does the same for model instances based upon changes to the parent view (typing in a text field, tapping and dragging, and other UI actions, etc.).

What is the most practical Solution to Data Management using SQLite on the iPhone?

I'm developing an iPhone application and am new to Objective-C as well as SQLite. That being said, I have been struggling w/ designing a practical data management solution that is worthy of existing. Any help would be greatly appreciated.
Here's the deal:
The majority of the data my application interacts with is stored in five tables in the local SQLite database. Each table has a corresponding Class which handles initialization, hydration, dehydration, deletion, etc. for each object/row in the corresponding table. Whenever the application loads, it populates five NSMutableArrays (one for each type of object). In addition to a Primary Key, each object instance always has an ID attribute available, regardless of hydration state. In most cases it is a UUID which I can then easily reference.
Before a few days ago, I would simply access the objects via these arrays by tracking down their UUID. I would then proceed to hydrate/dehydrate them as I needed. However, some of the objects I have also maintain their own arrays which reference other object's UUIDs. In the event that I must track down one of these "child" objects via it's UUID, it becomes a bit more difficult.
In order to avoid having to enumerate through one of the previously mentioned arrays to find a "parent" object's UUID, and then proceed to find the "child's" UUID, I added a DataController w/ a singleton instance to simplify the process.
I had hoped that the DataController could provide a single access point to the local database and make things easier, but I'm not so certain that is the case. Basically, what I did is create multiple NSMutableDicationaries. Whenever the DataController is initialized, it enumerates through each of the previously mentioned NSMutableArrays maintained in the Application Delegate and creates a key/value pair in the corresponding dictionary, using the given object as the value and it's UUID as the key.
The DataController then exposes procedures that allow a client to call in w/ a desired object's UUID to retrieve a reference to the actual object. Whenever their is a request for an object, the DataController automatically hydrates the object in question and then returns it. I did this because I wanted to take control of hydration out of the client's hands to prevent dehydrating an object being referenced multiple times.
I realize that in most cases I could just make a mutable copy of the object and then if necessary replace the original object down the road, but I wanted to avoid that scenario if at all possible. I therefore added an additional dictionary to monitor what objects are hydrated at any given time using the object's UUID as the key and a fluctuating count representing the number of hydrations w/out an offset dehydration. My goal w/ this approach was to have the DataController automatically dehydrate any object once it's "hydration retainment count" hit zero, but this could easily lead to significant memory leaks as it currently relies on the caller to later call a procedure that decreases the hydration retainment count of the object. There are obviously many cases when this is just not obvious or maybe not even easily accomplished, and if only one calling object fails to do so properly I encounter the exact opposite scenario I was trying to prevent in the first place. Ironic, huh?
Anyway, I'm thinking that if I proceed w/ this approach that it will just end badly. I'm tempted to go back to the original plan but doing so makes me want to cringe and I'm sure there is a more elegant solution floating around out there. As I said before, any advice would be greatly appreciated. Thanks in advance.
I'd also be aware (as I'm sure you are) that CoreData is just around the corner, and make sure you make the right choice for the future.
Have you considered implementing this via the NSCoder interface? Not sure that it wouldn't be more trouble than it's worth, but if what you want is to extract all the data out into an in-memory object graph, and save it back later, that might be appropriate. If you're actually using SQL queries to limit the amount of in-memory data, then obviously, this wouldn't be the way to do it.
I decided to go w/ Core Data after all.