我在我的 iPhone 应用程序委托 (AppDelegate) 中检索/保留变量时遇到了一个非常奇怪的问题。最初,我可以逐步查看我的值是否已传递给 logfile(有问题的 NSString 变量),但是当从另一个类中检索 logfile 时(请参见下面的代码),它会出错。
这是我的 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];
“日志文件”作为“超出范围”返回,因此局部变量“s”是糊状的。
我在这里做错了什么?这对我来说没有意义。