0

我有一個非常奇怪的問題檢索/保留我的iPhone應用程序委託(AppDelegate)中的變量。最初,我可以一步步看到我的值傳遞給logfile(問題中的NSString變量),但是當從另一個類檢索日誌文件時(請參閱下面的代碼),它會出錯。iPhone應用程序委託變量不被保留

這裏是我的AppDelegate.h文件:

#import <UIKit/UIKit.h> 

@interface AppDelegate : NSObject <UIApplicationDelegate> { 
    UIWindow *_window; 

MainViewController *_mainViewController; 
NSString *logFile; 
} 

@property (nonatomic, retain) NSString *logFile; 
@property (nonatomic, retain) ProductClass *item; 
@property (nonatomic, retain) UIWindow *window; 

-(void)appendToLog:(NSString *)textToLog; 
@end 

這裏是我的AppDelegate.m:

#import "AppDelegate.h" 
#import "MainViewController.h" 

@implementation AppDelegate 

@synthesize window = _window; 
@synthesize logFile; 

- (void) applicationDidFinishLaunching:(UIApplication *)application {  
_window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; 

_mainViewController = [[MainViewController alloc] init]; 
UINavigationController *_navigationController = [[UINavigationController alloc] initWithRootViewController:_mainViewController]; 

//Initialize the product class 
    [self appendToLog:@"Application loaded"]; 

    [_window addSubview:_navigationController.view]; 
    [_window makeKeyAndVisible]; 
} 

-(void)appendToLog:(NSString *)textToLog { 
//Append the log string 
if(logFile!=nil) { 
    NSString *tmp = [[logFile stringByAppendingString:textToLog] stringByAppendingString:@"\n"]; 
    logFile = tmp; 
} 
else { 
    NSString *tmp = [textToLog stringByAppendingString:@"\n"]; 
    logFile = tmp; 
} 
} 

@end 

當我使用調用(從另一個類):

AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate]; 
NSString *s = [appDelegate logFile]; 

「logfile」回到「超出範圍」,因此局部變量「s」很糟糕。

我在這裏做錯了什麼?這對我沒有意義。

回答

3

您應該將logFile = tmp;替換爲self.logFile = tmp;,因爲您需要使用「自我」。分配一個ivar以便代碼調用正確的settor方法時使用前綴。實際上,您只是將伊娃分配給自動發佈的對象實例,而不是保留它。自己。」前綴確保代碼執行正確的操作。沒有它,你只是分配變量而不保留它。

+0

這仍然給我同樣的錯誤行爲(應用程序不會崩潰,只是不會返回任何值)。 – Brett 2010-06-29 23:27:42

+0

更新:我包括self.logfile後清理和重建,現在它工作得很好!謝謝! – Brett 2010-06-29 23:39:46

-1

UIApplication類參考 - UIApplication指派並不保留委託。 您需要首先初始化您的AppDelegate實例。

+0

@lucius有合適的解決方案。您不應該在任何地方初始化您的應用程序委託,您總是希望通過'UIApplication'獲取指向您的應用程序委託的指針。讓系統擔心爲您進行初始化和保留。 – kubi 2010-06-29 23:24:28

0

我會建議在你的AppDelegate的賦值語句中加上前綴logfileself。例如,self.logfile = ...

相關問題