领域目标C - 使用零值解析NSInteger

时间:2015-05-20 14:24:53

标签: objective-c realm zero nsinteger

我实际上正在使用Realm Objective-C,这是我的问题:

我有一个Web服务返回:

{
    "id": 1,
    "name": "Project 1",
    "summary": "",
    "description": "description project 1 ...",
    "amountTargeted": 0,
    "amountReached": 0,
    "beginDate": 1432044917000,
    ...
    ... 
}

当我尝试使用此方法解析响应时:

 [Project createOrUpdateInDefaultRealmWithValue:projectDictionary];

我有这个错误:

'RLMException', reason: 'Invalid value '0' for property 'amountReached''

在我的项目模型中,我声明了amourReached:

@property NSInteger amountReached;

我做了一些测试,这个问题只出现在值为零的情况下。

我认为问题来自于这个方法,当它为零时返回false:

static inline bool nsnumber_is_like_integer(NSNumber *obj)
{
        const char *data_type = [obj objCType];
        // FIXME: Performance optimization - don't use strcmp, use first char in data_type.
        return (strcmp(data_type, @encode(short)) == 0 ||
        strcmp(data_type, @encode(int)) == 0 ||
        strcmp(data_type, @encode(long)) ==  0 ||
        strcmp(data_type, @encode(long long)) == 0 ||
        strcmp(data_type, @encode(unsigned short)) == 0 ||
        strcmp(data_type, @encode(unsigned int)) == 0 ||
        strcmp(data_type, @encode(unsigned long)) == 0 ||
        strcmp(data_type, @encode(unsigned long long)) == 0);
}

注意:我添加一个断点并尝试一些日志:

(lldb) p number
(NSNumber *) $6 = 0x15e76f50 @"0"
(lldb) po number
0
(lldb) p nsnumber_is_like_integer(number)(why ???)
(bool) $3 = false
(lldb) p nsnumber_is_like_integer(@0)(Why different of the first ?)
(bool) $5 = true
(lldb) p nsnumber_is_like_integer(@1)
(bool) $4 = true

如果您有任何想法,请提前感谢,这是一个领域问题还是来自我的代码的问题?

1 个答案:

答案 0 :(得分:0)

我找到了解决方案,我将类型从NSInteger更改为double,并且知道每件事情都可以。

@property NSInteger amountReached; //Old way
@property double amountReached; //Working way

我不确定这是正常的,对我来说,NSInteger应该没问题,如果有人作为解释:)。