문제

I am new to iOS programming, and writing a practice app to do task based on user location.

What I would like to have is to have a MyLocationManager wrapper class with a simple static function, something like

+(CLLocation *) getCurrentLocation;

So it can be called universally. However I found that usually the way to retrieve location is to implement the CLLocationManagerDelegate interface to have a succeed/fail handler, and usually the code is placed in the controller.

I am wondering if there's a suggested way to make such a centralized utility class like I mentioned, and wrap the retrieve location code nicely without having it exist in many different controllers?

도움이 되었습니까?

해결책

IMO, what you want to archive is not the best practice. I think the tidiest way in this case is using block as a completion hander. It will look like this

@implementation YourController

-(void)updateLocationAndDoSomething
{
    [Utilities startUpdateLocationWithCompletionHandler: ^ (CLLocationCoordinate2D location, BOOL *successed){
        //your custom code here
    }];
}
@end

here is a easy to understand tutorial about block http://www.appcoda.com/objective-c-blocks-tutorial/ in case you don't know how to

Second way, using delegation, your controller will look like this

@implementation YourController

-(void)gotLocationAndDoSomething:(CLLocationCoordinate2D) location
{
    //your custom code here
}

-(void)failedToGetLocation
{

}
@end

If you try to place them all into one Utility class, maybe it's possible in some cases, but it will get ugly very soon and hard to maintain.

다른 팁

Might not be the ideal way, but for now, store the variable in you're appDelgate and grab it from there whenever you need it.

If you need to call the function more than once, then yes, crests a Utils class and put all the utilities/other methods there.

Include the class where you need it and get your location.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top