NSInteger is set to 0, but returns nil

I have an NSInteger in my class like

In @interface:

NSInteger currentRow; @property (assign) NSInteger currentRow; 

In @implementation:

 @synthesize currentRow; 

Executing [self setCurrentRow:0] seems to work fine, but using [self currentRow] just for some reason returns null, I don’t know why. When using breakpoints, I can see that the currentRow value is 0 , so it set a penalty, but I cannot return the value.

+8
objective-c cocoa macos
source share
3 answers

In Objective-C, it is important to distinguish between objects and primitive types.

An object always saved as a pointer, which is the location of the object in memory. A pointer is just a number. With NSLog you can use %p to see this value. You can also display it in the debugger, for example: print myObject . The pointer is displayed as a hexadecimal number with the prefix 0x . nil is essentially zero zero ( 0x0000 ). When you select an object, you will get a pointer that is not non-zero. When you assign an object to a variable, you simply copy the memory address, not duplicate the object. With NSLog you can use %@ to print the description object. In the debugger, for example: print-object myObject .

Primitive types , such as NSInteger , are not objects. Instead of storing a pointer, you usually just keep the value. When you assign an NSInteger variable, you make a copy of the value. You can see the value in the debugger using print . Or like this: NSLog("%ld", (long)currentRow) . When you assign a primitive, you copy its value. Do not use %@ or print-object with primitives - they expect objects.

(I say β€œusually you just keep the value” because you can also create pointers to primitive types. In situations like yours, however, this is not necessary.)

[self currentRow] returns 0, just like you set it. (Moreover, since Objective-C guarantees the initialization of instance variables, it will return 0, even if you do not set it.)

The problem is that you are expecting a pointer to an object. How you fix your code depends on how you use it:

  • If you are using print-object currentRow , change it to print currentRow .
  • If you are using NSLog("%@", currentRow) , change it to NSLog(%"ld", (long)currentRow) .
  • If you use currentRow somewhere else where an object is required, change your instance variable and property types to NSNumber * , the object type. Install it using [self setCurrentRow:[NSNumber numberWithInt:0]] .
+15
source share

NSInteger is not an object, it is typedef'd for int or something like that. Thus, if you set currentRow to 0 and then try to return it, null (aka 0) will be completely correct.

+6
source share

The getter method will be synthesized as - (NSInteger)currentRow , so it should work fine. But how do you check if this works? With NSLog(@"%@", ...) ? Than you should use %d .

If you want this to be an object, you must use the NSNumber and retain property.

+3
source share

All Articles