0

在我的应用程序中,我正在读取 NSMutableArray 并将其写入 NSUserDefaults。该数组包含如下所示的对象:

头文件:

#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

有人可以帮我弄这个吗?我迷路了

4

1 回答 1

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不是这样,您的编码和解码都可以。

编码、解码和读取方法上的断点会很快为您缩小问题范围。

高温高压

于 2015-01-12T19:34:51.650 回答