繁体   English   中英

NSMutableString访问问题

[英]NSMutableString access problem

因此,我想在功能之外访问并显示格式化的日期。 对于日期格式,我正在使用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并在代码中的其他位置(例如,另一个函数等)访问它。

我考虑过创建这样的NSMutableStringNSMutableString* lastUpdated = [NSMutableString stringWithFormat:@"%@",dateString]; 并在其他地方访问lastUpdated ,但是该函数lastUpdated为空...您能帮上忙吗? 干杯

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

如果这样做,您将声明一个名为lastUpdated的局部变量。 即使存在另一个具有相同名称的全局变量,只要它在范围内(函数的生命周期),该局部变量都将隐藏该全局变量。

为了使这项工作有效,您需要在任何函数或方法之外的某个位置(可能在.m文件的顶部附近)声明一个全局lastUpdated

NSMutableString *lastUpdated;

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

extern NSMutableString *lastUpdated;

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

有两件事要知道:

  1. 这是C的基本知识,因此,如果您不熟悉C,则应查看C的作用域规则。了解全局变量,静态变量,局部变量,实例变量之间的区别(好吧,普通的旧C没有这些变量) )和一个参数。

  2. 全局变量是可怕的。 不要相信其他告诉你的人。 我提供上述建议可以帮助您解决当前的问题,但是更好的解决方案是弄清楚如何重构代码,从而避免使用全局变量。 (而且,IMO也无法解决这个问题。仅用于访问全局数据的单例只不过是花哨的全局变量而已。)

您应该像这样保留字符串。

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

现在尝试在外部访问。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM