gpt4 book ai didi

cocoa-touch - iOS/iPhone SDK : initWithCoder and encodeWithCoder not being called

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:57:53 24 4
gpt4 key购买 nike

我正在尝试保存一个名为 queueArray 的 NSMutableArray,以便在应用程序退出后可以再次加载它。我使用了一些教程来帮助我前进,这是我想出的代码。问题似乎是“initWithCoder”和“encodeWithCoder”没有被调用,没有 NSLog 调用,也没有在断点处停止。我已将 NSCoding 协议(protocol)添加到 .h 文件,我知道 queueArray 不是 nil,它包含 MPMediaItem。这是我用来尝试保存和加载数组的一些代码:

-(IBAction)saveQueuePressed {

NSString *rootPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *filePath = [rootPath stringByAppendingPathComponent:@"queueArray.archive"];

//should cause encodeWithCoder to be called
[NSKeyedArchiver archiveRootObject:queueArray toFile:filePath];

}

-(IBAction)loadQueuePressed {

NSString *rootPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *filePath = [rootPath stringByAppendingPathComponent:@"queueArray.archive"];

//should cause initWithCoder to be called
queueArray = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];

}

-(void)encodeWithCoder:(NSCoder *)coder {

NSLog(@"encodeWithCoder");

[coder encodeObject:queueArray forKey:@"savedQueueArray"];
}



-(id)initWithCoder:(NSCoder *)decoder {

NSLog(@"initWithCoder");

queueArray = [decoder decodeObjectForKey:@"savedQueueArray"];

return self;

}

任何帮助将不胜感激!

最佳答案

encodeWithCoder:initWithCoder 方法在您存档/取消存档响应它们的对象时被调用。据我了解,您的类中有这些方法,但您实际归档的对象 (queueArray) 不是该类的实例,它是一个 NSMutableArray

如果你想保存你的整个对象,你可以改变你的 saveQueue 方法

-(IBAction)saveQueuePressed {

NSString *rootPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *filePath = [rootPath stringByAppendingPathComponent:@"queueArray.archive"];

// saving the array shouldn't, but saving the self object
//should cause encodeWithCoder to be called:
[NSKeyedArchiver archiveRootObject:self toFile:filePath];
}

但是如果你只想保存数组,我想你可以只使用saveQueuePressedloadQueuePressed,我认为你不需要encode/初始化 WithCoder: 方法

更新:也许你的路不对。尝试

NSString *rootPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *filePath = [[rootPath stringByAppendingPathComponent:@"queueArray.archive"] stringByExpandingTildeInPath]];

关于cocoa-touch - iOS/iPhone SDK : initWithCoder and encodeWithCoder not being called,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3753671/

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