gpt4 book ai didi

Objective-C NSKeyedUnarchiver 卸载

转载 作者:行者123 更新时间:2023-12-03 17:59:26 25 4
gpt4 key购买 nike

在某些 AppDelegate 类中,我有属性 NSDictionary *dict;

applicationDidFinishLaunching 中,我加载它的方式如下:

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

然后,我就有了按钮点击的导出。但在点击操作处理程序中我无法访问 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

最佳答案

您应该使用属性访问器而不是直接访问实例变量:

在您的 .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

这样做有几个原因,但在这种情况下最重要的是访问器方法可以处理实例变量的内存管理。

关于Objective-C NSKeyedUnarchiver 卸载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8779818/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com