2012-01-08 50 views
0

在一些AppDelegate類我有屬性NSDictionary *dict;Objective-C的NSKeyedUnarchiver卸載

applicationDidFinishLaunching我加載它想:

dict = (NSDictionary*) [NSKeyedUnarchiver unarchiveObjectWithFile: 
         @"/Users/username/Desktop/storage"]; 

然後,我有出路按鈕點擊。但是在click-action處理程序中,我無法訪問dict的元素。我究竟做錯了什麼?

編輯: 這裏的.h文件:

#import <Cocoa/Cocoa.h> 

@interface tttAppDelegate : NSObject <NSApplicationDelegate> { 
    NSWindow *window; 
    NSDictionary *dict; 
} 

@property (assign) IBOutlet NSWindow *window; 
- (IBAction)click:(id)sender; 

@end 

和的.m文件:

#import "tttAppDelegate.h" 

@implementation tttAppDelegate 

@synthesize window; 

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification 
{ 
    dict = (NSDictionary*) [NSKeyedUnarchiver unarchiveObjectWithFile:@"/some/storage"]; 

    NSLog(@">>>>>>> %@", [dict valueForKey:@"test"]); // ok 
} 

- (IBAction)click:(id)sender { 
    NSLog(@">>>>>>> %@", [dict valueForKey:@"test"]); // fail 
} 
@end 
+0

請張貼更多您的代碼。是否是一個實例變量? – 2012-01-08 18:35:36

+0

@AndrewMadsen完成,謝謝 – sashab 2012-01-08 19:10:44

+0

還有一個問題:您是使用ARC(自動引用計數)還是手動內存管理? – 2012-01-08 19:16:52

回答

1

您應該使用屬性訪問,而不是直接訪問您的實例變量:

在你的.h文件中:

@interface tttAppDelegate : NSObject <NSApplicationDelegate> { 
    NSWindow *window; 
    NSDictionary *dict; 
} 

@property (assign) IBOutlet NSWindow *window; 
@property (nonatomic, retain) NSDictionary *dict; 

- (IBAction)click:(id)sender; 

@end 

在您的m:

@implementation tttAppDelegate 

@synthesize window; 
@synthesize dict; 

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification 
{ 
    self.dict = (NSDictionary*) [NSKeyedUnarchiver unarchiveObjectWithFile:@"/some/storage"]; 

    NSLog(@">>>>>>> %@", [self.dict valueForKey:@"test"]); // ok 
} 

- (IBAction)click:(id)sender { 
    NSLog(@">>>>>>> %@", [self.dict valueForKey:@"test"]); // fail 
} 
@end 

有幾個原因這樣做,但在這種情況下,最重要的是,這樣的存取方法可以處理實例變量的內存管理。