我有一個非常奇怪的問題檢索/保留我的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」很糟糕。
我在這裏做錯了什麼?這對我沒有意義。
這仍然給我同樣的錯誤行爲(應用程序不會崩潰,只是不會返回任何值)。 – Brett 2010-06-29 23:27:42
更新:我包括self.logfile後清理和重建,現在它工作得很好!謝謝! – Brett 2010-06-29 23:39:46