Storing an additional NSNumber in the underlying data

In my main data model, I have an object with the optional NSNumber attribute.

How to check if the value in this attribute is really specified?

When I test zero ... doesn't work.

[self numberAttribute] == nil // always returns NO 

When I test a null int value, this does not work.

 [[self numberAttribute] intValue] == 0 // always returns no 

Essentially, [[self numberAttribute] intValue]] returns what looks suspiciously like a pointer to a memory address.

Does anyone know what I'm doing wrong?

EDIT: OK, the error was in a completely unrelated part of the code. NSNumber and Core Data function exactly as you would expect. However, I'm going to move on to the proposed approach to make the attribute non-optional and specify 0 as the default value.

Just posting this note here a little, for those who looked at this question, I delete it.

+6
objective-c iphone cocoa-touch core-data nsnumber
source share
3 answers

According to the documentation ,

You can indicate that the attribute is optional, that is, you do not need to have a value. In general, however, you are not recommended to do this, especially for numerical values ​​(as a rule, you can get better results using the required attribute with the default value - in the model - 0). The reason for this is because SQL has a special comparison behavior for NULL, which is unlike Objective-C nil. NULL in the database does not match 0, and a search of 0 will not match NULL columns.

 false == (NULL == 0) false == (NULL != 0) 

In addition, NULL in the database is not equivalent to an empty string or an empty data block:

 false == (NULL == @"") false == (NULL != @"") 

So try a test with NULL that is not null. Better yet, set the default value and change the attribute, which is optional. This is what I ended up doing in my models, and in practice it works very well.

Edit: See my comment above. I tried to create a new managed entity with an optional attribute that was not set, and it was zero.

 BOOL isNil = ([newManagedObject numberAttribute] == nil); //equals YES 

Another edit: I went back to this later and checked the object loaded from the cache in the debugger (gdb is your friend!). He tried to access memory location 0x0, which is NULL.

+5
source share

If you get a large value back that looks like a pointer, is it possible NaN (not a number)?

If so, you can check:

  isnan([[self numberAttribute] doubleValue]) 

Or perhaps it's some other constant along the NSNotFound lines (although there are probably more specific kernel data).

0
source share

If it looks like a pointer, it can be a pointer to an instance of NSNumber . Make sure you don’t have a mismatch between the underlying data model and the class (for example, NSInteger where NSNumber* is expected).

If you have a scalar in your class, then you need to note that you yourself are in setNilValueForKey:

0
source share

All Articles