gpt4 book ai didi

objective-c - 需要一个关于如何存储/加载我的自定义类以进行 iOS 开发的简单示例

转载 作者:行者123 更新时间:2023-12-01 19:26:35 25 4
gpt4 key购买 nike

我有以下objective-c类:

@interface LatLongData {
NSMutableString *_lat;
NSMutableString *_long;
NSMutableString *_altitude;
}

-(LatLongData*) initWithLat:(NSMutableString*) latitude Long:(NSMutableString*) longitude Altitude:(NSMutableString*) altitude;

@end

如何存储/加载该对象的实例?我尝试过使用这样的代码:
LatLongData *data = [[LatLongData alloc] initWithLat:_lat Long:_long Altitude:_altitude];

// Save
NSData *theData = [NSKeyedArchiver archivedDataWithRootObject:data];
[[NSUserDefaults standardUserDefaults] setObject:theData forKey:LatLongDataKey];

//...

// Load
NSData *loadedData = [[NSUserDefaults standardUserDefaults] dataForKey:LatLongDataKey];
LatLongData *ldata = (LatLongData *)[NSKeyedUnarchiver unarchiveObjectWithData:theData];

但我没有运气......
我知道我应该阅读有关 Core Data 的所有内容。我会,但在这一点上,让我的小样本工作会非常好。

最佳答案

您需要使用 NSCoding protocol和你的类(class)。@interface LatLongData <NSCoding>
以下是一些协议(protocol)方法:

- (id)initWithCoder:(NSCoder *)aDecoder
{
if ((self = [super init])) {
lat = [[aDecoder decodeObjectForKey:@"lat"] copy];
long = [[aDecoder decodeObjectForKey:@"long"] copy];
alt = [[aDecoder decodeObjectForKey:@"alt"] copy];
}
return self;
}

- (void)encodeWithCoder:(NSCoder *)aCoder
{
[aCoder encodeObject:lat forKey:@"lat"];
[aCoder encodeObject:long forKey:@"long"];
[aCoder encodeObject:alt forKey:@"alt"];
}

附言您需要更换 theData在你的最后一行 loadedData

关于objective-c - 需要一个关于如何存储/加载我的自定义类以进行 iOS 开发的简单示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7061750/

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