开发者

How does Object A wait for Object B to complete getting location data in its Core Location Delegate, so it can use the data?

  • Object A calls Object B to sta开发者_开发知识库rt Core Location and acquire location data.
  • Object B is also the Core Location Delegate and receives a successful callback, data is received.
  • Object B's delegate stops Core Location as only one location data point is needed.

  • Object A wants to use that location data, and does have access to the location variables in Object B

The problem is that Object A tries to use those empty variables before Object B has acquired the Core Location data. Object A races on, Object's B's Core Location data is not yet available.

How does Object A effectively "wait", or get notified that the data is there and its ok to proceed ?

Thanks, Ric


Simple way, NSNotificationCenter.

In Object B header file:

extern NSString *const kLocationKey;
extern NSString *const kIGotLocationNotification; // whatever name you like

In Object B implementation file:

// assign a string we will use for the notification center
NSString *const kIGotLocationNotification = @"Any text you like here";
NSString *const kLocationKey = @"Location";


// in the method where you stop core location
CLLocation *loc;

// create a dictionary object with the location info
NSDictionary *dict = [NSDictionary dictionaryWithObject:loc forKey:kLocationKey];

// you post a notification to the default center
[[NSNotificationCenter defaultCenter] postNotificationName:kIGotLocationNotification object:self userInfo:dict];

In Object A implementation file:

// inside your init method 
// become an observer with the default center
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleIGotLocation:) name:kIGotLocationNotification object:nil];

// inside your dealloc
// don't forget to remove yourself from the notification default center
[[NSNotificationCenter defaultCenter] removeObserver:self];


// create the selector that will receive the notification
- (void)handleIGotLocation:(NSNotification *)pNotification {
    NSLog(@"Name: %@", [pNotification name]);
    NSLog(@"Object: %@", [pNotification object]);

    // the user info is going to contain the dict with your location
    NSLog(@"UserInfo: %@", [pNotification userInfo]);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜