0

所以我想在我的函数之外访问和显示一个格式化的日期。对于我使用的日期格式NSDateFormatter,效果很好..

我的函数 ( didFinishUpdatesSuccessfully) 执行一些操作,如果成功则显示一个UIAlertView包含格式化日期的内容。一切正常..

- (void) didFinishUpdatesSuccessfully {

    //--- Create formatted date
    NSDate *currDate = [NSDate date];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
        [dateFormatter setDateFormat:@"dd/MM/YYYY - hh:mm:ss a"];
    NSString *dateString = [dateFormatter stringFromDate:currDate];     // dateString contains the current date as a string

    [dateFormatter release];


    //--- UIAlertView
    NSString *title = @"The update has been performed!";

    UIAlertView *alert = [[UIAlertView alloc] initWithTitle: title
                                                    message: dateString
                                                   delegate: nil
                                          cancelButtonTitle: [FileUtils appResourceForKey:@"UPDATE_GENERAL_BUTTON_TITLE_OK"]
                                          otherButtonTitles: nil];
    [alert show];
    [alert release];

    //--- create new string
    // NSMutableString* lastUpdated = [NSMutableString stringWithFormat:@"%@",dateString];

}

我现在想将值写入dateString全局NSStringNSMutableString 在代码中的其他位置访问它,例如另一个函数等。

我想创建一个NSMutableString这样的: NSMutableString* lastUpdated = [NSMutableString stringWithFormat:@"%@",dateString];并访问lastUpdated其他地方,但这个功能的外面lastUpdated是空的......你能帮忙吗?干杯

4

2 回答 2

0
NSMutableString* lastUpdated = [NSMutableString stringWithFormat:@"%@",dateString];

如果你这样做,你就声明了一个名为lastUpdated. 即使有另一个同名的全局变量,只要它在范围内(函数的生命周期),这个局部变量也会隐藏全局变量。

为了使这项工作,您需要lastUpdated在任何函数或方法之外的某个地方声明一个全局,可能靠近 .m 文件的顶部:

NSMutableString *lastUpdated;

然后,您可以从 .m 文件中的任何位置访问该变量。如果您想在其他 .m 文件中访问它,您需要在相应的头 (.h) 文件中添加一个 extern 声明:

extern NSMutableString *lastUpdated;

使用该声明,您可以lastUpdated在包含该头文件的任何文件中使用。

有两件事要知道:

  1. 这是基本的 C 内容,所以如果看起来不熟悉,您应该查看 C 的范围规则。了解全局变量、静态变量、局部变量、实例变量之间的区别(好吧,普通的旧 C 没有这些) 和一个参数。

  2. 全局变量是可怕的。不要相信任何告诉你的人。我提供上面的建议来帮助解决你眼前的问题,但更好的解决方案是弄清楚如何重构你的代码,这样你就可以避免对全局变量的需要。(而且 IMO 单例也不是答案。仅用于访问全局数据的单例只不过是花哨的全局变量。)

于 2011-07-25T04:47:07.963 回答
0

你应该保留这样的字符串。

NSMutableString* lastUpdated;
lastUpdated = [[NSMutableString stringWithFormat:@"%@",dateString] retain];

现在尝试在外部访问。

于 2011-07-25T04:56:24.790 回答