[英]Using Global Variables to communicate values between classes
因此,我的简单想法是创建一个允许用户通过电子邮件报告其位置的纬度和经度坐标的应用程序。 您单击该按钮,将通过MessageUI框架显示电子邮件屏幕,“收件人”,“主题”和“正文”字段已经预先输入,用户只需单击“发送”即可。
我的问题是,我需要将纬度和经度坐标包含在电子邮件正文中。 就像我需要的那样,那些坐标变量是在-(void)CLLocationManager函数中生成的,并变成了字符串。 问题是,电子邮件是从另一个函数-(void)displayComposerSheet发送的,我不知道如何将经/纬度字符串放入要发送的电子邮件正文中。 在通过Google进行了一些尝试之后,我遇到了“全局变量”的想法。 这似乎是我需要实现的。 许多消息来源都说“在应用程序委托中声明变量,然后您就可以在代码中的任何位置使用它们”,或者至少这就是我要表达的意思。 再次强调,我是这个游戏的新手。 因此,看来,如果我要在proxy.m文件而不是project .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];
}
// NSString *msgLat = self->latitude.text; do not do this
// NSString *msgLong = self->longitude.text; or this
NSString *msgLat = latitude.text;
NSString *msgLong = longitude.text;
不需要全局变量(假设两个方法都属于同一类)。
为此,您不需要全局变量。 只需在控制器类中创建实例变量(ivars),然后将经度/纬度存储在其中。 然后,在displayComposerSheet方法中,使用先前计算的值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.