领域, - [__ NSCFString timeIntervalSince1970]:无法识别的选择器发送到实例

时间:2016-02-14 17:15:26

标签: ios objective-c database objective-c-blocks realm

我请求你的帮助。 我想保存我对Realm db的响应。

这是我的测试模型

 @interface CurrencyInfo : RLMObject

    @property (strong, nonatomic) NSDate *date;

    - (instancetype)initWithJSONDictionary:(NSDictionary *)jsonDictionary;

    @end
    RLM_ARRAY_TYPE(CurrencyInfo)


    @implementation CurrencyInfo

    - (instancetype)initWithJSONDictionary:(NSDictionary *)jsonDictionary {
        self = [super init];
        if(self) {
            _date = jsonDictionary[@"date"];
        }

        return self;
    }

@end

这是我的api经理班

#import <Foundation/Foundation.h>

typedef void(^ResponseHandler)(BOOL success, id object, NSError *error);

@interface RestApiManager : NSObject <NSURLSessionDataDelegate, NSURLSessionDelegate, NSURLSessionTaskDelegate>

+(instancetype)sharedManager;

-(void)fetchCurrencyInfoWithCompletionHandler:(ResponseHandler)handler;

@end

@implementation RestApiManager {

    NSURLSession *_session;
    NSURLSessionDataTask *_dataTask;

}

+ (instancetype)sharedManager {
    static id sharedInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^(void) {
        sharedInstance = [self new];
    });

    return sharedInstance;
}

- (void)fetchCurrencyInfoWithCompletionHandler:(ResponseHandler)handler {

    _dataTask = [self.session dataTaskWithURL:[NSURL URLWithString:@"http://resources.finance.ua/ru/public/currency-cash.json"] completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response;
        if (httpResponse.statusCode == 200) {
            NSDictionary *result = [NSJSONSerialization JSONObjectWithData:data options:nil error:&error];
            CurrencyInfo *info = [[CurrencyInfo alloc] initWithJSONDictionary:result];
            NSLog(@"%@", info.date);
            handler(YES, info, error);
        }
    }];
    [_dataTask resume];
}

- (NSURLSession *)session {
    if (!_session) {
        NSURLSessionConfiguration *sessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration];
        _session = [NSURLSession sessionWithConfiguration:sessionConfiguration];
    }
    return _session;
}

@end

这是我的ViewController类

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    __weak typeof(self) weakSelf = self;

    [[RestApiManager sharedManager] fetchCurrencyInfoWithCompletionHandler:^(BOOL success, CurrencyInfo * object, NSError *error) {

        [weakSelf saveInDB:object];

    }];
}

- (void)saveInDB:(CurrencyInfo *) info{
    RLMRealm *realm = [RLMRealm defaultRealm];
    [realm transactionWithBlock:^(void) {
        [realm addObject:info];
    }];
}

@end

所以,没什么特别的,我只是想保存对db的响应。 但我有下一期

  

- [__ NSCFString timeIntervalSince1970]:无法识别的选择器发送到实例0x78784c60

完整的堆栈跟踪

2016-02-14 18:12:45.784 TestRealmDB[4814:240669] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFString timeIntervalSince1970]: unrecognized selector sent to instance 0x78784c60'
*** First throw call stack:
(
    0   CoreFoundation                      0x0150da14 __exceptionPreprocess + 180
    1   libobjc.A.dylib                     0x00fcee02 objc_exception_throw + 50
    2   CoreFoundation                      0x01516d63 -[NSObject(NSObject) doesNotRecognizeSelector:] + 275
    3   CoreFoundation                      0x014546bd ___forwarding___ + 1037
    4   CoreFoundation                      0x0145428e _CF_forwarding_prep_0 + 14
    5   TestRealmDB                         0x0013da14 _ZL20RLMDateTimeForNSDateP6NSDate + 36
    6   TestRealmDB                         0x00133699 _ZL11RLMSetValueP13RLMObjectBasejP6NSDate + 89
    7   TestRealmDB                         0x001320c6 RLMDynamicSet + 1334
    8   TestRealmDB                         0x00176ffa RLMAddObjectToRealm + 2810
    9   TestRealmDB                         0x002729b8 -[RLMRealm addObject:] + 56
    10  TestRealmDB                         0x000cc3c3 __27-[ViewController saveInDB:]_block_invoke + 51
    11  TestRealmDB                         0x00271c6b -[RLMRealm transactionWithBlock:error:] + 107
    12  TestRealmDB                         0x00271bab -[RLMRealm transactionWithBlock:] + 91
    13  TestRealmDB                         0x000cc320 -[ViewController saveInDB:] + 224
    14  TestRealmDB                         0x000cc18d __29-[ViewController viewDidLoad]_block_invoke + 141
    15  TestRealmDB                         0x000cd214 __57-[RestApiManager fetchCurrencyInfoWithCompletionHandler:]_block_invoke + 436
    16  CFNetwork                           0x039cd087 __75-[__NSURLSessionLocal taskForClass:request:uploadFile:bodyData:completion:]_block_invoke + 48
    17  CFNetwork                           0x039e1153 __49-[__NSCFLocalSessionTask _task_onqueue_didFinish]_block_invoke + 353
    18  Foundation                          0x00c7b96f __NSBLOCKOPERATION_IS_CALLING_OUT_TO_A_BLOCK__ + 12
    19  Foundation                          0x00b9f85f -[NSBlockOperation main] + 108
    20  Foundation                          0x00b7fce4 -[__NSOperationInternal _start:] + 697
    21  Foundation                          0x00b7fa24 -[NSOperation start] + 83
    22  Foundation                          0x00b7f862 __NSOQSchedule_f + 245
    23  libdispatch.dylib                   0x02e756fd _dispatch_client_callout + 14
    24  libdispatch.dylib                   0x02e5d33e _dispatch_queue_drain + 1065
    25  libdispatch.dylib                   0x02e5cc89 _dispatch_queue_invoke + 563
    26  libdispatch.dylib                   0x02e5e732 _dispatch_root_queue_drain + 442
    27  libdispatch.dylib                   0x02e5e571 _dispatch_worker_thread3 + 108
    28  libsystem_pthread.dylib             0x0319743e _pthread_wqthread + 1050
    29  libsystem_pthread.dylib             0x03194f72 start_wqthread + 34
)
libc++abi.dylib: terminating with uncaught exception of type NSException

1 个答案:

答案 0 :(得分:2)

我认为问题出在-[CurrencyInfo initWithJSONDictionary]方法中,在这一特定行中:

_date = jsonDictionary[@"date"];

jsonDictionary不包含NSDate个实例,而是一个字符串。 (NSJSONSerialization不会为你做这样的转换。)

您必须将存储在字典中的NSString转换为NSDate,可能使用NSDateFormatter