سؤال

I'm creating an iOS app with 4 tabs (4 view controllers) that gets CoreLocation updates and displays the location along with some other data in various representations (table view, map view, etc)

I only want to use one CoreLocationManager, so I can only have one delegate, but 4 view controllers need to know about the updates so that the visible view can be updated

What is the best way to let my view controllers know that there has been a location update?

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

المحلول 2

The BEST method is probably to simply use the notification center. Rather than a @protocol, put a NSString * const you're using for the notification:

NSString * const kMyNotificationString @"MyNotificationString"

Now, when the would-be delegates need to respond, it's as simple as:

[[NSNotificationCenter defaultCenter] postNotificationName:kMyNotificationString
                                                    object:nil];

Any object that needs to respond to this notification can #import this header file (so it gets the NSString * const-ed notification name and then and start listening to the notification as such:

[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(myMethod)
                                             name:kMyNotificationString
                                           object:nil];

Just don't forget to remove observers when (or before) you dealloc.


Alternatively, there's this approach... but it's not really that great, and I'd actually recommend against it.

Rather than a single delegate property, you could have a NSArray property that handles the "delegates" (make sure you have an "addDelegate" method that only adds weak references to the array). Then, when you need all of these objects to respond to a change:

for (id<MyProtocol> object in self.arrayOfDelegates) {
    if ([object respondsToSelector:@selector(myMethod)]) {
        [object myMethod];
    }
}

نصائح أخرى

The simplest is to post a notification rather than using a delegate. Delegates are 1:1 where as notifications are 1:many. Problem is you still need at least one delegate which will post the notifications.

If you want, you can create an NSProxy object which you can set as the location manager delegate and which internally holds a list of other delegates and forwards all of the received method calls to all of the internally managed delegates.

The easiest way is implement one delegate that forwards messages as notifications, this way any number of objects can subscribe as observers for those notifications.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top