我有一个名为Account的类,有6个属性,其中一个属性是c结构。我无法弄清楚如何使用NSCoding来遵守结构。我将如何编码和解码c struct属性。结构是app_config_t类型。
结构
typedef struct app_config_t
{
pj_pool_t *pool;
pjsua_config cfg;
pjsua_logging_config log_cfg;
pjsua_media_config media_cfg;
pjsua_transport_config udp_cfg;
pjsua_transport_config rtp_cfg;
pj_bool_t ringback_on;
pj_bool_t ring_on;
int ringback_slot;
int ringback_cnt;
pjmedia_port *ringback_port;
int ring_cnt;
SystemSoundID ring_id;
CFRunLoopTimerRef ring_timer;
} app_config_t;
一个名为'Account'的Objective-C类,其属性为App_config
#pragma mark - NSCoding
- (void) encodeWithCoder:(NSCoder *)aCoder
{
[aCoder encodeObject:self.Username forKey:@"username"];
[aCoder encodeObject:self.Password forKey:@"password"];
[aCoder encodeObject:self.Server forKey:@"server"];
[aCoder encodeInt:self.Account_id forKey:@"Account_id"];
[aCoder encodeInt:self.Call_id forKey:@"Call_id"];
//trying to save this object, is this even correct
NSMutableData *data = [NSMutableData dataWithBytes:&_App_config length:sizeof(app_config_t)];
NSKeyedArchiver *App_config_Archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
[aCoder encodeObject:App_config_Archiver forKey:@"App_config"];
}
- (id)initWithCoder:(NSCoder *)aDecoder
{
if (self = [super init])
{
self.Username = [aDecoder decodeObjectForKey:@"username"];
self.Password = [aDecoder decodeObjectForKey:@"password"];
self.Server = [aDecoder decodeObjectForKey:@"server"];
self.Account_id = [aDecoder decodeIntForKey:@"Account_id"];
self.Call_id = [aDecoder decodeIntForKey:@"Call_id"];
self.App_config = ?????????
}
return self;
}
答案 0 :(得分:0)
您当前的编码代码有错误。 Archiver使用您为NSKeyedArchiver
提供的可变数据来存储编码数据。因此复制app_config_t
结构是没用的。
您需要使用NSKeyedArchiver
对结构的每个字段进行编码。它具有原始类型的编码器。同样在app_config_t
结构中,我看到的字段不是基本类型,而是复杂类型。所以你也需要为这些字段定制编码。
- (void) encodeWithCoder:(NSCoder *)aCoder
{
[aCoder encodeObject:self.Username forKey:@"username"];
[aCoder encodeObject:self.Password forKey:@"password"];
[aCoder encodeObject:self.Server forKey:@"server"];
[aCoder encodeInt:self.Account_id forKey:@"Account_id"];
[aCoder encodeInt:self.Call_id forKey:@"Call_id"];
// this data will have encoded structure
NSMutableData *data = [NSMutableData data];
NSKeyedArchiver *App_config_Archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
// for all fields from structure you need to use such encoders
[App_config_Archiver encodeBool:_App_config.ringback_on forKey:@"ringback_on"];
// encode data itself
[aCoder encodeObject:data forKey:@"App_config"];
}
答案 1 :(得分:0)
您应该能够将结构视为内存缓冲区并使用NSCoder的encodeBytes function来执行此操作:
- (void)encodeBytes:(const void * _Nullable)byteaddr
length:(NSUInteger)length