0

我已将我的应用与 UTI 相关联,以便用户可以启动 KML 附件。在我的通用应用程序的 iPad 应用程序委托中,我可以看到 launchOptions 并从中获得正在启动的文件的 NSURL。我想将它存储为全局,以便我可以从我的应用程序的其他地方访问它,我正在使用一个名为 Engine 的单例来执行此操作。这是我的应用程序代表:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {    

    Engine *myEngine=[Engine sharedInstance];

    StormTrackIpad *newVC=[[StormTrackIpad alloc] initWithNibName:@"StormTrackIpad" bundle:nil];
    [window addSubview:newVC.view];

    NSURL *launchFileURL=(NSURL *)[launchOptions valueForKey:@"UIApplicationLaunchOptionsURLKey"];

    myEngine.launchFile=launchFileURL;

    /* Show details of launched file

    NSString *message =launchFileURL.absoluteString;
    NSString *title = [NSString stringWithFormat:@"Opening file"];             
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title message:message delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
    [alert show];
    [alert release];

    */

    [window makeKeyAndVisible];

    return YES;
}

我的引擎类如下所示:

//  Engine.h

#import <Foundation/Foundation.h>

@interface Engine : NSObject {
    NSURL *launchFile;
}

+ (Engine *) sharedInstance;

@property (nonatomic, retain) NSURL *launchFile;

@end

//  Engine.m

#import "Engine.h"

@implementation Engine
@synthesize launchFile;

static Engine *_sharedInstance;

- (id) init
{
    if (self = [super init])
    {
        // custom initialization
    }
    return self;
}

+ (Engine *) sharedInstance
{
    if (!_sharedInstance)
    {
        _sharedInstance = [[Engine alloc] init];
    }
    return _sharedInstance;
}

@end

我的问题是,当我尝试从应用程序中其他地方的引擎(从视图控制器)访问 launchFile 变量时,调试器将 Engine.launchFile 的值显示为 . 我正在访问这样的变量:

- (void)viewDidLoad {
    [super viewDidLoad];

    Engine *myEngine=[Engine sharedInstance];

    NSURL *launchFile=myEngine.launchFile;

     NSString *title = [NSString stringWithFormat:@"Opening file"];             
     UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title message:launchFile.absoluteString  delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
     [alert show];
     [alert release]; 
}

有什么帮助吗?

4

1 回答 1

0

乍一看,您的代码看起来不错 - 您可以在 myEngine.launchFile = 上设置断点以查看 myEngine 指向的内容吗?这应该确保您的单例代码正常工作。

另外,您是否检查过 [launchOptions valueForKey:@"UIApplicationLaunchOptionsURLKey"] 肯定返回一个对象?你的意思是输入这个:

[launchOptions valueForKey:UIApplicationLaunchOptionsURLKey];

山姆

P 你应该阅读关于创建单例对象的这个问题的答案,你应该把一些覆盖放到你的引擎类中;)

于 2010-06-22T13:12:41.433 回答