سؤال

I have an object that can be selected by a user click. With the current requirements of the app, at any time, there is no more than one of these items selected at any point during app execution.

I implemented a mechanism to enforce this, as follows:

  • Each of these objects has a unique identifier as a property.
  • When each object is created, it subscribes to the NSNotificationCenter listening for the MY_OBJECT_SELECTED notification.
  • When each object is selected, it posts the MY_OBJECT_SELECTED notification, with its unique Id as part of the userInfo dictionary.
  • Then, when each object receives the notification, it checks to see if its id is the same as the one in the userInfo. If it is, it does nothing, but if it isn't, it sets itself to unselected.

Is this a decent approach to the problem? If not, how would you do it?

هل كانت مفيدة؟

المحلول

It is a decent way of doing it, although it is not very efficient. The more objects you have, the more time you spend comparing IDs. The easiest way is to store your object pointers and IDs in a map table (or similar) and remember the last selected object. Whenever you select a new object, you clear the selection flag of the last selected object, then look up the new object and set its selection flag. It requires you to keep a collection of your objects, though.

The time required to update selections with this approach is independent of the number of objects you have.

نصائح أخرى

If the object is spread all over the app,i.e. if it is a member in various classes. You can have a global object of same type and assign it to only that object which has been touched. In steps it will be like:

  • Have a global variable of object type.
  • At any object touch assign globalObject = currentObject;
  • do all operations on globalObject throughout app like calling methods and modifying object members(have a check for nil to ensure safety).
  • Reassign to different object with new touch.
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top