持久化launchOptions NSURL作为全局变量

时间:2010-06-22 11:47:06

标签: iphone variables global iphone-sdk-3.2

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

- (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;
}

My Engine类看起来像这样:

//  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]; 
}

任何帮助?

1 个答案:

答案 0 :(得分:0)

乍一看你的代码看起来还不错 - 你能在myEngine.launchFile上设置一个断点吗?只是为了看看myEngine指向的是什么?这应该确保您的单例代码正常工作。

另外,您是否检查过[launchOptions valueForKey:@“UIApplicationLaunchOptionsURLKey”]肯定会返回一个对象?你的意思是打字:

[launchOptions valueForKey:UIApplicationLaunchOptionsURLKey];

萨姆

P你应该阅读关于创建单例对象的answer to this question,你应该在引擎类中添加一些覆盖;)

相关问题