gpt4 book ai didi

ios nsCoding 设置但不调用 encodeWithCoder

转载 作者:行者123 更新时间:2023-11-29 02:17:59 25 4
gpt4 key购买 nike

我正在尝试使用 NSCoding 来保存和恢复应用程序状态。我以前没用过。

在我的应用程序中,协议(protocol)方法 encodeWithCoder 和 initWithCoder 从未被调用。我已经准备了一个具有相同问题的简单测试用例,希望有人能告诉我我做错了什么。

这是我的 CodingTest.h 文件:

#import <Foundation/Foundation.h>

@interface CodingTest : NSObject <NSCoding>
- (void) saveData;
- (void) loadData;
- (id) init: (int) testValue;

@end

这里是 CodingTest.m

#import "CodingTest.h"
@interface CodingTest()
@property int testInt;
@end

@implementation CodingTest
- (id) init: (int) testValue
{
_testInt = testValue;
return self;
}

-(void) loadData
{
CodingTest *newTestClass = [NSKeyedUnarchiver unarchiveObjectWithFile:@"testfile"];
}

-(void) saveData
{
[NSKeyedArchiver archiveRootObject:self toFile:@"testfile"];
}

- (void) encodeWithCoder:(NSCoder *)encoder {
[encoder encodeInt:_testInt forKey:@"intValue"];
}

- (id)initWithCoder:(NSCoder *)decoder {
int oldInt = [decoder decodeIntForKey:@"intValue"];
return [self init:oldInt];
}

@end

我这样调用它:

CodingTest *testCase = [[CodingTest alloc] init:27];
[testCase saveData ];
[testCase loadData];

init、saveData 和 loadData 都被调用了。但是永远不会调用 encodeWithEncoder 和 initWithCoder。我做错了什么?

最佳答案

问题是“testfile”本身不是一个有效的文件名。如果将其更改为“tmp/testfile”,它就可以正常工作。

有趣的是,如果在编码时得到错误的文件名,它不会调用解码函数,即使解码调用没有指定文件名。

关于ios nsCoding 设置但不调用 encodeWithCoder,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28524108/

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