2011-12-14 5 views
2

기본적으로 사용자의 현재 위치에 가까운 위치 (장소) 목록을 출력하는 XML 파일을로드하고 구문 분석하는 Xcode 프로젝트가 있습니다. 원래 경도와 위도 좌표를 하드 코딩하여 내 XML이 올바르게 파싱되었는지 확인했지만 현재 사용자에게 가장 가까운 위치를 결정하기 위해 사용자의 현재 위치를 전달하려고 시도하고 있습니다 (상점과 유사). 파인더). xml 파일을로드하는 대리자 클래스 파일과 사용자의 현재 위치를 처리하는 rootViewController 파일이 있습니다. 내 문제는 하나의 클래스에서 매개 변수를 대리자 클래스로 전달하는 가장 좋은 방법을 모른다는 것입니다. 미안하지만 기본적으로 잘 알고 있습니다. :)Objective-C 위임 클래스에 전달하는 매개 변수

여기에 기초의 두 발췌 문장 내가 무엇을의 :

RootViewController.m

- (void)viewDidLoad { 
    [super viewDidLoad]; 

    // Get Current Location 
    locationManager = [[CLLocationManager alloc] init]; 
    locationManager.delegate = self; 
    locationManager.distanceFilter = kCLDistanceFilterNone; // whenever we move 
    locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters; // 100 m 
    [locationManager startUpdatingLocation]; 

    appDelegate = (XMLAppDelegate *)[[UIApplication sharedApplication] delegate]; 

} 

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation 
{ 
    int degrees = newLocation.coordinate.latitude; 
    double decimal = fabs(newLocation.coordinate.latitude - degrees); 
    int minutes = decimal * 60; 
    double seconds = decimal * 3600 - minutes * 60; 
    NSString *lat = [NSString stringWithFormat:@"%d° %d' %1.4f\"", degrees, minutes, seconds]; 

    degrees = newLocation.coordinate.longitude; 
    decimal = fabs(newLocation.coordinate.longitude - degrees); 
    minutes = decimal * 60; 
    seconds = decimal * 3600 - minutes * 60; 
    NSString *longt = [NSString stringWithFormat:@"%d° %d' %1.4f\"", degrees, minutes, seconds]; 

    NSLog(@"longt Value: %@", longt); 
} 

XMLAppDelegate.m

- (void)applicationDidFinishLaunching:(UIApplication *)application { 

    //This code is incorrect (displays 'null') I want to display the values defined in the locationManager Method on RootViewController.m 
    NSLog(@"lat Value: %@", currentLocation.coordinate.latitude); 

    // Longitude and Latitude codes are hard-coded. I want to change this to dynamic values which are defined in the locationManager Method on RootViewController.m 
    NSURL *url = [[NSURL alloc] initWithString:@"http://www.domain.com/phpsqlsearch_genxml.php?lat=-33.870017&lng=151.206547&radius=25"]; 

    //More code here.... 
} 

결과 (NSLog)를 RootViewController.m 파일에는 표시 할 수 있지만 XMLAppDelegate.m 파일에는 표시 할 수 없습니다. RootViewController.m에서 XMLAppDelegate.m으로 매개 변수를 전달하는 가장 좋은 방법을 찾아야합니까?

더 이상 필요한 정보가 있으면 알려주십시오.

환호

+3

applicationDidFinishLaunching이 호출 될 것이고, 이후에 viewDidLoad가 발생하므로 appDidFinishLaunching에 변경 사항이 적용되지 않습니다. –

+0

다른 클래스에서 appDelegate의 객체/값을 사용해야하며 그 반대는 마찬가지입니다. – utsabiem

+0

또한 currentLocation.coordinate.latitude는 숫자 (정수 또는 부동 소수점 숫자)입니다. NSLog가 NSObject로 액세스하려고 시도했을 때 충돌이 발생했을 것입니다. NSLog에서는 적절한 형식 지정자 (정수의 경우 "% d", 부동 소수점의 경우 "% f")를 사용해야합니다. –

답변

1

나는 애플이 그렇게하는 것처럼 말하고 싶다. 예를 들어 UITableView을 예로 들어 보겠습니다.

첫째, delegatehelp 타 클래스, 당신은 helper 클래스로 delegate 생각해야하는 오브젝트 (나는이 전적으로 사실이 아니다 알고)입니다.
그래서 UITableView 케이스에서 UITableView는 어떤 일을하기 위해 델리게이트에게 요청하고 있으며, 묻기 때문에 그것은 return을 듣고 있습니다.
당신은 jQuery과에가 있어야 얼마나 많은 부분에 대해 당신은 대리인의 master에 정보를 다시 전송되는 UITableView

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView 

에서이 전화를받을 때.

두 번째로 메서드 서명을 자세히 살펴보면 master이 매개 변수로 전달된다는 것을 알 수 있으므로 delegate은 필요한 경우 더 많은 정보를 얻기 위해 master을 요청할 수 있습니다.

그래서이 그것에게 몇 가지 질문을 할 수 delegate을의에이 작품에서, master 포인터를 얼마나, 그리고 delegate은 전화를받을 때 master의 알 수. delegate에는 master에 대한 포인터를 저장할 수 있지만 표시되는 것처럼 필요하지는 않습니다.

즉, 항상 delegate 또는 master에 대한 참조를 갖고 있으며 이에 대한 참조 정보가 있으면 문제가되지 않습니다.

위임자는 마스터에 정보를 제공하는 위임자 여야합니다. 따라서 코드를 올바르게 읽으면 역변환을 수행합니다.

1

귀하의 클래스가 서로 통신 할 수있는 기능과 같이 보일 것입니다 :

RootViewController.h :

#import <Foundation/Foundation.h> 
#import <CoreLoation/CoreLocation.h> 
#import <UIKit/UIKit.h> 
#import "XMLAppDelegate.h" 

@interface RootViewController: UIViewController <CLLocationManagerDelegate, CustomDelegateProtocol> { 
    float lon, lat; 
} 

@end 

RootViewController.m :

#import "RootViewController.h" 

@implementation RootViewController 

// super 

- (void)viewDidLoad { 
    [super viewDidLoad]; 

    // Get Current Location 
    locationManager = [[CLLocationManager alloc] init]; 
    locationManager.delegate = self; 
    locationManager.distanceFilter = kCLDistanceFilterNone; // whenever we move 
    locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters; // 100 m 
    [locationManager startUpdatingLocation]; 

    appDelegate = (XMLAppDelegate *)[[UIApplication sharedApplication] delegate]; 

} 

// CLLocationManagerDelegate 

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation { 
    int degrees = newLocation.coordinate.latitude; 
    double decimal = fabs(newLocation.coordinate.latitude - degrees); 
    int minutes = decimal * 60; 
    double seconds = decimal * 3600 - minutes * 60; 
    NSString *lat = [NSString stringWithFormat:@"%d° %d' %1.4f\"", degrees, minutes, seconds]; 

    degrees = newLocation.coordinate.longitude; 
    decimal = fabs(newLocation.coordinate.longitude - degrees); 
    minutes = decimal * 60; 
    seconds = decimal * 3600 - minutes * 60; 
    NSString *longt = [NSString stringWithFormat:@"%d° %d' %1.4f\"", degrees, minutes, seconds]; 

    NSLog(@"longt Value: %@", longt); 
} 

// CustomDelegateProtocol 

@synthesize lon = lon, lat = lat; 

@end 

XMLAppDelegate.h :

#import <Foundation/Foundation.h> 
#import <UIKit/UIKit.h> 

@protocol CustomDelegateProtocol 

@property (assign) float lon; 
@property (assign) float lat; 

@end 

@interface XMLAppDelegate: NSObject <UIApplicationDelegate> { 
    // whatever instance variables you need, put them here 
    id <CustomDelegateProtocol> delegate; 
} 

@end 

XMLAppDelegate.m :이 도움이

#import "XMLAppDelegate.h" 

@implementation XMLAppDelegate 

/* 
- (void)applicationDidFinishLaunching:(UIApplication *)application { 
    // BTW: don't use this to obtain location info if you're NOT setting up your UI from code... 
    // It has (conceptually, but also practically) be done in your view controller. 
    // That's why it is called a view controller: it "glues" view and logic code together 
    // and that way you won't even need the delegate 
    // I also recommend using the -application:didFinishLaunchingWithOptions: method. This one is deprecated. 
} 
*/ 

- (BOOL) application:(UIApplication *)app didFinishLaunhingWithOptions:(NSDictionary *)launchOpts { 
    // set up initial stuff, etc... 
    // and if you *really, badly* want to use the delegation model, here you are: 
    NSString *urlString = [[NSString alloc] initWithFormat: @"http://www.domain.com/phpsqlsearch_genxml.php?lat=-%f&lng=%f&radius=25", self.delegate.lat, self.delegate.lon]; 
    NSURL *url = [[NSURL alloc] initWithString:urlString]; 
    [urlString release]; 

    // do whatever you want to 


    return YES; 
} 

@end 

희망.

+0

두 가지 훌륭한 반응! 이 두 가지에 대한 귀하의 도움에 감사드립니다. – user1068733

관련 문제