UITableViewCells and NSURLConnection - asynchronous

I have a custom UITableViewCell, and when the user clicks a button i make a request to a server and update the cell. I do this with a NSUrlConnection and it all works fine (this is all done inside the cell class) and once it returns it fires a delegate method and the tableivew controller handles this. However when i create the cell in the tableview, i use the dequeue method and reuse my cells. So if a cell has fired a asynchronous nsurlconnection, and the cell gets reused whilst this is still going on, will this in turn erase the current connection? I just want to make sure that if the cell is reused, the actual memory that was assigned to the cell is still there so the connection can fulfil its duty??

You can customize the behavior of a UITableViewCell by subclassing it and overriding the -perpareForReuse method. In this case, I would recommend destroying the connection when the cell is dequeued. If the connection should still keep going, you’ll need to remove the reference to it (set it to nil) and handle its delegate methods elsewhere.

It's never a good idea to keep a reference of a connection or any data that you want to display in a cell, no matter how much of effort you put into it afterward to work around to arising problems. Your approach will never work reliable.
In your case, if the user quickly scrolls the table view up and down, your app will start and possibly cancel dozens of connections and yet never finishes to load something. That will be an awful user experience, and may crash the app.
Better you design your app with MVC in mind: the cell is just a means to display your model data, nothing else. It's the View in this architectural design.
For that purpose the Table View Delegate needs to retrieve the Model's properties which shall to be displayed for a certain row and setup the cell. The model encapsulates the network connection. The Controller will take the role to manage and update change notification and process user inputs.
A couple of Apple samples provide much more details about this topic, and there is a nice introduction about MVC, please go figure! ;)
http://developer.apple.com/library/ios/#documentation/general/conceptual/devpedia-cocoacore/MVC.html
The "Your Second iOS App: Storyboards" also has a step by step explanation to create "Data Controller Classes". Quite useful!
Now, when using NSURLConnection which updates your model, it might become a bit more complex. You are dealing with "lazy initializing models". That is, they may provide some "placeholder" data when the controller accesses the property instead of the "real" data when is not yet available. The model however, starts a network request to load it. When it is eventually loaded, the model must somehow notify the Table View Controller. The tricky part here is to not mess with synchronization issues between model and table view. The model's properties must be updated on the main thread, and while this happens, it must be guaranteed that the table view will not access the model's properties. There are a few samples which demonstrate a few techniques to accomplish this.

Related

How to distinguish user edits from data model updates with Qt widgets?

I'm trying to implement MVC in Qt using a data model ported from another platform. I have several widgets onscreen that each listen to the same model to render the data. The user can also interact with these widgets, edit them, and thus push changes back into the model.
The specific problem I have is that if my (ported) data model changes and I push data into eg a QTreeWidgetItem with setData, the widget emits an itemChanged signal. This in turn triggers the controller code that is monitoring user edits, and causes it to push the same data back to the model. Unless I insert data comparison somewhere, I end up with an infinite loop.
Is there some way for the controller to quietly update the item's data without emitting itemChanged? Alternately, is there a better way to distinguish between user edits on a widget and programmatic changes? I am simply listening for itemChanged.
Is there some way for the controller to quietly update the item's data
without emitting itemChanged?
I hope not. I would not like it if I had a view, which shows wrong data because someone secretly changed the model. I am afraid, you have to conjure up something yourself. You have to modify your controller. Not emitting itemChanged when it does.... horrible idea.
I was thinking, what you could do. Expect no complete solution. I just looked around how I would do it. You must subblass your model and override the setData method. Then you can distinguish changes by the role. Qt::EditRole or you can create your own user defined role. The itemChanged signal must be emitted in any case. Else your views would be wrong. But in your model subclass you could implement a new signal 'dataChangedByUser' or whatever, which could be emitted additionally to itemChanged. How your controller handles this....

UI thread stalls on loading and updating a RadGridView object

Afternoon all,
I'm currently profiling a rather large C# WPF app, trying to eliminate a few performance issues. One involves a 5-8 second stall that occurs when switching to a particular (rather large) UserControl. I've narrowed this down to a RadGridView contained in this UserControl that's taking a long time to load and update itself, stalling the UI thread and making the entire application unresponsive. Obviously, we'd like to eliminate this stall if possible.
I have tried stripping away any custom styles and DataTriggers on the grid, but while this acted to reduce load on the UI thread in general, the stall still remained, seemingly undiminished. Through ANTS Profiler, it seems that the measuring and layout of the grid is mostly to blame, along with some loading of XAML templates. With no grid rows, the UserControls loads significantly faster, and it seems that adding just a small number of rows is enough to bring about this stall. The grid has virtualization enabled for rows and columns, but this doesn't seem to help. The call graph is tremendously deep when examined, and it seems to be calls that raise update notifications, update layout, load XAML and, above all, measure child FrameworkElements that are to blame.
For a couple of potential solutions, I'm thinking about keeping the UserControl in memory but hidden to reduce the costs of switching to it, or populating the grid, perhaps incrementally, well after the UserControl has loaded. There might be a lot of work with the former, as the control subscribes to a number of things, which would need to be connected to, disconnected from and reconnected to as appropriate. The latter might also involve a fair bit of work, but might be a better solution, because then at least we could try to mitigate the stalling ourselves, or at least warn the user when it was occurring.
If the problem persists, we're likely to ask Telerik to have a look at it, but I thought I'd ask here first in case anyone has encoutered such an issue before (not necessarily with RadGridView, even) and found a solution of some description.
Cheers.
The problem is you need a collection that implements ICollectionChanged properly.
Try this after adding all records to your source collection (one which should NOT raise any CollectionChanged events after each add), it works:
public void AddRange(List<TValue> values, int startingIndex)
{
// add all the items to your internal list, but avoid raising events.
// now raise CollectionChanged with an IList type.
CollectionChanged?.Invoke(collection, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, addedValues, startingIndex));
}
Notice we're passing IList<TValue>, NOT TValue. When it sees a list, it adds them ALL before processing. The startingValue is usually the .Count of the list before you started adding items.
Steps:
Subclass a collection type that doesn't already implement INotifyCollectionChanged. Plenty of open source examples are out there.
Add the method above and use it after you've added your items.
My RadGridView is binding against a QueryableCollectionView which uses this list as its SourceCollection. I don't know if you can bind against this list directly.
One strange behavior with RadGridView is that if you add say, a million records this way, it WILL be quick, but all the new rows will be blank, and you can watch RadGridView slowly populate them with data from the topmost new item down. My solution to this is to bind against QueryableCollection and set its PageSize sufficiently small so the users don't see this.

DDD along with collections

suppose I have a domain classes:
public class Country
{
string name;
IList<Region> regions;
}
public class Region
{
string name;
IList<City> cities;
}
etc.
And I want to model this in a GUI in form of a tree.
public class Node<T>
{
T domainObject;
ObservableCollection<Node<T>> childNodes;
}
public class CountryNode : Node<Country>
{}
etc.
How can I automatically retrieve Region list changes for Country, City list changes for Region etc.?
One solution is to implement INotifyPropertyChanged on domain classes and change IList<> to ObservableCollection<>, but that feels kinda wrong because why should my domain model have resposibility to notify changes?
Another solution is to have that responsibility put upon the GUI/presentation layer, if some action led to adding a Region to a Country the presentation layer should add the new country to both the CountryNode.ChildNodes and the domain Country.Regions.
Any thoughts about this?
Rolling INotifyPropertyChanged into a solution is part of implementing eventing into your model. By nature, eventing itself is not out of line with the DDD mantra. In fact, it is one of the things that Evans has implied that has been missing from his earlier material. I don't remember exactly where, but he does mention it in this video; What I've learned about DDD since the book
In and of itself, impelemnting an eventing model is actually legitimate in the domain, because of the fact it introduces a decoupling between the domain and the other code in your system. All you are doing is saying that your domain has the capability of notifying interested parties in the fact that something has changed. It is the responsibility of the subscriber, then, to act upon it. I think that where the confusion lies is that you are only using an INotifyPropertyChanged implementation to relay back to an event sink. That event sink will then notify any subscribers, via a registered callback, that "something" has happened.
However, with that being said, your situation is one of the "fringe" scenarios that eventing does not apply all that well to. You are looking to see if you need to repopulate a UI when the list itself changes. At work, the current solution that we have uses an ObservableCollection. While it does work, I am not a fan of it. On the flip side, publishing a fact that one or more items in the list have changed is also problematic. For example, how would you determine the entropy of the list to best determine that it has changed?
Because of this, I would actually consider this to not be a concern of the domain. I do not think that what you are describing would be a requirement of the domain owner(s), but rather an artifact of the application architecture. If you were to query the services in the domain after the point that the change is made, they would return correctly and the application would still be what is out of step. There is nothing actually wrong inside the world of the domain at this momeent in time.
So, there are a few ways that I could see this being done. The most inefficient way would be to continually poll for changes directly against the model. You could also consider having some sort of marker that indicates that the list is dirty, although not using the domain model to do so. Once again, not that clean of a solution. You can apply those principles outside of the domain, however, to come up with a working solution.
If you have some sort of a shared caching mechanism, i.e. a distributed cache, you could implement a JIT-caching/eviction approach where inserts and updates would invalidate the cache (i.e. evict the cached items) and a subsequent request would load them back in. Then, you could actually put a marker into the cache itself that would indicate something identifiable as to when that item(s) was/were rebuilt. For example, if you have a cache item that contains a list of IDs for region, you could store the DateTime that it was JIT-ed along with it. The application could then keep track of what JIT-ed version it has, and only reload when it sees that the version has changed. You still have to poll, but it eliminates putting that responsibility into the domain itself, and if you are just polling for a smaller bit of data, it is better than rebuilding the entire thing every time.
Also, before overarchitecting a full-blown solution. Address the concern with the domain owner. It may be perfectly acceptable to him/her/them that you simply have a "Refresh" button or menu item somewhere. It is about compromise, as well, and I am fairly sure that most domain owners would have a preference of core functionality over certain types of issues.
About eventing - most valuable material I've seen comes from Udi Dahan and Greg Young.
One nice implementation of eventing which I'm eager to try out can be found here.
But start with understanding if that's really necessary as Joseph suggests.

Mate Framework - Check data before making remote call

Until recently I have been using cairngorm as a framework for flex. However, in this latest project I have switched to Mate. It's` still confusing me a little as I kind of got used to leaving data in the model. I have a couple of components which rely on the same dataset(collection).
In the component the creation complete handler sends a 'GiveMeMyDataEvent' which is caught by one of the eventmaps. Now in cairngorm in my command class I would have had a quick peek in the model to decide whether I need to get the data from the server or not and then either returned the data from the model or called the db.
How would I do this in Mate? Or is there a better way to go about this, I'm trying to utilize the data that has already been recieved from the server, but at the same time I'm not sure I have loaded the data or not. If a component which uses that same data has been instantiated then the answer is yes otherwise no.
Any help/hints greatly appreciated.
Most things in Mate are indirect. You have managers that manage your data, and you set up injectors (which are bindings) between the managers and your views. The injectors make sure your views are synchronized with your managers. That way the views always have the latest data. Views don't get updated as a direct consequence of dispatching an event, but as an indirect consequence.
When you want to load new data you dispatch an event which is caught by an event map, which in turn calls some service, which loads data and returns it to the event map, and the event map sticks it into the appropriate manager.
When the manager gets updated the injectors make sure that the views are updated.
By using injectors you are guaranteed to always have the latest data in your views, so if the views have data the data is loaded -- unless you need to update periodically, in which case it's up to you to determine if data is stale and dispatch an event that triggers a service call, which triggers an update, which triggers the injectors to push the new data into the views again, and round it goes.
So, in short the answer to your question is that you need to make sure you use injectors properly. If this is a too high-level answer for you I know you can get more help in the Mate forums.
I ran into a similiar situation with the app I am working on at the moment, and found that it is easily implemented in Mate when you start thinking about having two events.
The first event being something like DataEvent.REFRESH_MY_DATA. This event is handled by some DataManager, which can decide to either ignore it (since data is already present in the client and considered up to date), or the manager can dispatch an event like DataEvent.FETCH_MY_DATA.
The FETCH_MY_DATA event triggers a service call in the event map, which updates a value in the manager. This update is property-injected into the view, happy days :)

howto avoid massive notification in DataBinding

I guess it's quite a common problem in databinding scenarios.
What do you usually do, if you are running a batch update and want to avoid that a propertychanged-dependend calculations/actions/whatever are executed for every single update?
The first thing which usually comes to my mind, is to either introduces a new boolean or unhook/hook the eventhandler, ...
What I don't like about this approaches is:
they introduce new complexity (has to be maintained, ...)
they are error prone, because you have to make sure that a suppressed notifications are sent afterwards
I'm wondering if somebody addressed this problem already in a more convenient way that is more easy to handle?
tia
Martin
Edit: not to missunderstand me. I know about the things .NET provides like RaiseListChangedEvents from BindingList, ... They are all addressing the problem in more/less the same way as I described, but I'm searching for a different way which doesn't have to listed drawbacks.
Maybe I'm on the wrong track, but I though I give it a try here...
There isn't a single one-size-fits-all solution, unfortunately. I've applied or seen the following solutions:
There are two singals. One signal is emitted when the change comes from a user action, the other always fires. This allows to distinguish between changes in the UI and updates by code.
A boolean to protect code
The property event framework stops propagating events automatically when a value didn't really change.
A freeze/thaw method on the signal or the signal manager (i.e. the whole framework)
A way to merge signals into a single one. You can do N updates and they get collected into M signals where M <= N. If you change the same property 100 times, you still only get 1 signal.
Queuing of signals (instead of synchronous execution). The queuing code can then merge signals, too. I've used this with great success in an application that doesn't have a "Save" button. All changes are saved to the database as you make them. When you change a text, the changes are merged over a certain time (namely until the previous DB update returns) and then, they are committed as a single change.
An API to set several values at once; only a single signal is emitted.
The signal framework can send signals at different levels of granularity. Say you have a person with a name. When you change the name, you get two signals: One for the name change and one "instance field changed". So if you only care "has something changed", then you can hook into the instance instead of all the fields.
What platform? The post makes me think .NET.
What is the underlying objects? For example, BindingList<T> as a source allows you to disable notifications by setting RaiseListChangedEvents to false while doing the update.
Other than that (or similar); yes, disconnect the binding during big updates
The easiest route to take is to use the BindingSource component for your data binding. Instead of binding your controls to a particular object (or IList), use that object as the DataSource for the BindingSource, then bind the controls to the BindingSource.
The BindingSource class has SuspendBinding() and ResumeBinding() functions.

Resources