gpt4 book ai didi

iphone - 单例不会从应用程序委托(delegate)持久化到另一个 View Controller 中

转载 作者:行者123 更新时间:2023-12-03 20:25:53 27 4
gpt4 key购买 nike

点击此链接:How do I archive two objects using NSKeyedArchiever?我能够归档一个数组和一个单例对象。我可以在 didFinishLaunchingWithOptions 处归档并正确取消归档它。

但是,我的单例对象不会在应用程序委托(delegate)之后持续存在。在下一个 View Controller 中,单例变量返回到其默认值,即使在 didFinishLaunchingWithOptions 中,我执行了 NSLog 并进行了验证。这是一个例子,

在应用程序中didFinishLaunchingWithOptions:

Singleton *singleton = [Singleton sharedSingleton];
NSData *data = [NSData dataWithContentsOfFile:path];
NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
singleton = [unarchiver decodeObjectForKey:@"singleton"];
[unarchiver finishDecoding];

NSLog(@"解码后单例排序:%@", [单例排序]);//输出:字母表

然后,我分配/初始化一个 viewController 并将其设置为我的导航 Controller 的 Root View Controller :

navController = [[UINavigationController alloc] initWithRootViewController:viewController];

在 viewController -> viewWillAppear 中,

我调用排序函数:[ self 排序...];

并且在排序函数中,我调用单例类:单例*singleton = [单例sharedSingleton];但现在, NSLog(@"singleton sort: %@", [singleton sort]); //输出:amount NOT Alphabet

我可以发布我的单例代码,但我知道它有效。事实上,在我的设置 View Controller 中,如果我更改 [singleton sort] 变量,它将在所有 View Controller 中持续存在。

这让我很困惑为什么我的单例对象不能从应用程序委托(delegate)持久化到我的 View Controller 。如有任何提示/提示,我们将不胜感激。

谢谢!!!

编辑:单例类实现

在 Singleton.m 中:

static Singleton *shared = NULL;

+ (id)sharedSingleton
{
@synchronized(self)
{
if ( !shared || shared == NULL )
{
// allocate the shared instance, because it hasn't been done yet
NSLog(@"Allocating Singleton...");
shared = [[Singleton alloc] init];
}
return shared;
}
}


- (id)init
{
if ( self = [super init] )
{
sort = [[NSString alloc] initWithString:@"amount"];
showTutorial = YES;
}
return self;
}

-(id)initWithCoder:(NSCoder *)aDecoder
{
[super init];
[self setSort:[aDecoder decodeObjectForKey:@"sort"]];
[self setShowTutorial:[aDecoder decodeBoolForKey:@"showTutorial"]];

return self;
}

-(void)encodeWithCoder:(NSCoder *)aCoder
{
[aCoder encodeObject:sort forKey:@"sort"];
[aCoder encodeBool:showTutorial forKey:@"showTutorial"];
}

最佳答案

在您的代码中,您只是更新当前上下文中的单例指针的值,而不是sharedSingleton实例

尝试在 Singleton 类中创建一个方法,该方法使用 unarchiver 对象更新 Singleton 类,如下所示:

[[Singleton sharedSingleton] loadArchive:unarchiver];

或者(我认为更好)将代码移到 Singleton init 函数中。

关于iphone - 单例不会从应用程序委托(delegate)持久化到另一个 View Controller 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6523289/

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