簡體   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