使用NSKeyedUnarchiver读取错误的类类型

时间:2015-01-12 17:25:05

标签: ios objective-c nsobject nskeyedarchiver nskeyedunarchiver

在我的应用中,我正在向NSUserDefaults读取和编写NSMutableArray。此数组包含如下所示的对象:

头文件:

#import <Foundation/Foundation.h>
#import <CoreLocation/CoreLocation.h>

@interface WorkLocationModel : NSObject

@property (nonatomic, strong) CLRegion *geoLocation;

@end

实施档案:

#import "WorkLocationModel.h"

@implementation WorkLocationModel

-(id)init {
// Init self
self = [super init];
if (self)
{
    // Setup
}
return self;
}

- (void)encodeWithCoder:(NSCoder *)coder {
[coder encodeObject:self.geoLocation forKey:@"geoLocation"];
}

-(void)initWithCoder:(NSCoder *)coder {
self.geoLocation = [coder decodeObjectForKey:@"geoLocation"];
}

@end

这是我阅读我的清单的方式:

这是在我加载数组的ViewController中,当它应该是一个WorkLocationModel对象时,oldArray似乎记录了NSKeyedUnarchiver类型的1项(正确数量):

    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSData *workLocationsData = [defaults objectForKey:@"workLocations"];
if (workLocationsData != nil)
{
    NSArray *oldArray = [NSKeyedUnarchiver unarchiveObjectWithData:workLocationsData];

    if (oldArray != nil)
    {
        _workLocations = [[NSMutableArray alloc] initWithArray:oldArray];
        NSLog(@"Not nil, count: %lu", (unsigned long)_workLocations.count);
    } else
    {
        _workLocations = [[NSMutableArray alloc] init];
    }
} else
{
    _workLocations = [[NSMutableArray alloc] init];
}

这就是我将WorkLocationModel对象添加到我的数组的方法:

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
// Create a sample work location
WorkLocationModel *newModel = [[WorkLocationModel alloc] init];
newModel.geoLocation = currentRegion;
[_workLocations addObject:newModel];

// Save the new objects
[defaults setObject:[NSKeyedArchiver archivedDataWithRootObject:_workLocations] forKey:@"workLocations"];

// Synchronize the defaults
[defaults synchronize];

错误发生在这里的if语句中(进一步到我的ViewController),我在那里比较了两个CLRegions。

region 是一个函数参数。

    for (WorkLocationModel *currentWorkLocationModel in _workLocations)
{
    if ([region isEqual:currentWorkLocationModel.geoLocation])
    {
        // Found a match
    }
}

我已经完成了代码,但我不明白为什么会这样,异常消息:

-[NSKeyedUnarchiver geoLocation]: unrecognized selector sent to instance 0x174108430
2015-01-12 18:23:20.085 myApp[1322:224462] *** Terminating app due to
uncaught exception 'NSInvalidArgumentException', reason: '-[NSKeyedUnarchiver geoLocation]:
unrecognized selector sent to instance

有人可以帮我吗?我迷失了

1 个答案:

答案 0 :(得分:0)

initWithCoder:方法就像任何其他init方法一样 - 它必须调用super并返回一个实例。你的方法应该是:

- (instancetype) initWithCoder:(NSCoder *)coder
{
   self = [super init];
   if(self)
      self.geoLocation = [coder decodeObjectForKey:@"geoLocation"];
   return self;
}

如果你的超类实现了initWithCoder:,那么super调用将是[super initWithCoder:coder](同样适用于encodeWithCoder:) - NSObject不会这样你就行了在你的编码和解码中。

您的编码,解码和阅读方法的断点会很快缩小您的问题范围。

HTH