使用全局变量在类之间传递值

时间:2010-01-09 20:51:43

标签: iphone objective-c cocoa cocoa-touch email

所以我的想法是创建一个应用程序,允许用户通过电子邮件报告其位置的纬度和经度坐标。点击按钮,电子邮件屏幕通过MessageUI框架显示,To,Subject和Body字段已经预先输入,所需的只是用户点击“发送”。

我的问题是,我需要将纬度和经度坐标包含在电子邮件正文中。这些坐标变量在 - (void)CLLocationManager函数中生成,并转换为字符串,就像我需要的那样。问题是,电子邮件是从另一个函数发送的, - (void)displayComposerSheet,我无法弄清楚如何将lat / long字符串放入要发送的电子邮件正文中。经过一段时间的冲击,我遇到了全局变量的想法。这似乎是我需要实现的。很多消息来源都说“在应用程序代理中声明你的变量,然后你就可以在代码中的任何地方使用它们”,或者至少这就是我所说的意思。再说一遍,我会强调我对这个游戏很新。所以,似乎如果我要在delegate.m文件中创建我的纬度和经度字符串而不是项目.m文件,那么我将能够在闲暇时调用它们,然后将它们发送到我的电子邮件的正文。

我只是不知道所有“东西”应该去哪里。这是我到目前为止所做的事情(完美无缺)。我只需要用CLLocationManager生成的ACTUAL值替换我的默认纬度值“12.3456”和经度值“78.9012”。任何帮助将不胜感激。谢谢!

//Code that generates the Latitude and Longitude strings
//--------------------------------------------------------
- (void)locationManager:(CLLocationManager *)manager
    didUpdateToLocation:(CLLocation *)newLocation
           fromLocation:(CLLocation *)oldLocation


{
    //Breaks down the location into degrees, minutes, and seconds.

    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];    
    latitude.text = lat;
    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];
    longitude.text = longt;

}





//Code that prepares the email for sending
//------------------------------------------
-(void)displayComposerSheet 
{
    MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];
    picker.mailComposeDelegate = self;

    [picker setSubject:@"New Location Report!"];


    // Set up recipients
    NSArray *toRecipients = [NSArray arrayWithObject:@"pghapps2009@gmail.com"]; 

    [picker setToRecipients:toRecipients];


    // Fill out the email body text 
    NSString *message = @"user reported their location at:";
    NSString *msgLat = @"12.3456";
    NSString *msgLong = @"78.9012";

    NSString *emailBody = [NSString stringWithFormat:@"%@\nLatitude = %@\nLongitude = %@", message, msgLat, msgLong];


    [picker setMessageBody:emailBody isHTML:NO];

    [self presentModalViewController:picker animated:YES];
    [picker release];
}

2 个答案:

答案 0 :(得分:7)

//    NSString *msgLat = self->latitude.text; do not do this
//    NSString *msgLong = self->longitude.text; or this
NSString *msgLat = latitude.text;
NSString *msgLong = longitude.text;

不需要全局变量(假设两个方法都属于同一个类)。

答案 1 :(得分:1)

您不需要全局变量。只需在控制器类中创建实例变量(ivars),并将lat / long存入其中。然后,在displayComposerSheet方法中,使用先前计算的值。