0

I'm pretty new to Objective-C programming so please excuse the nebbish question. If I create NSInteger as follows:

@property (nonatomic) NSInteger myNumber;

is it assigned to some random integer a la 'C' or is it automatically assigned to '0'?

also, where is the most reasonable place to assign it, noting that this will be in a view controller that may or may not receive this value from another view controller.

At this point I'm being paranoid and using NSNumber so that at least I can test for nil but I was hoping to see if I could do this better.

ThinkBonobo
  • 15,487
  • 9
  • 65
  • 80
  • You could create your own test application to figure this out for yourself you know? Besides, it doesn't hurt any to initialise it yourself – hd1 Jan 04 '14 at 23:51
  • 3
    hd1 - The problem with just testing it myself is that I could be getting zero and it would not prove that it would always be 0 and its not something specific to my setup. @creker. Although the question asked is different the answer is definitely the same, alloc 0s out the value. Thanks for your help! – ThinkBonobo Jan 05 '14 at 00:07
  • @ThinkBonobo Read the SO answer referenced by creker. – zaph Jan 05 '14 at 00:28
  • Specifically, this answer will be helpful for you: http://stackoverflow.com/a/3115012/1445366 – Aaron Brager Jan 05 '14 at 00:31
  • Instance/property variables are always initied to zero/nil. – Hot Licks Jan 05 '14 at 00:36
  • @hd1 - A test case would prove nothing. You might get zero 1000 times and non-zero on the 1001st try, or after a recompile, or only if another app had run first or whatever. – Hot Licks Jan 05 '14 at 00:38

2 Answers2

1

Per Creger's comment,

I looked at the result for Are ints always initialized to 0?

NSInteger is indeed initialized to zero as are all class instance variables.

This is the comment on apples documentation:

The alloc method has one other important task, which is to clear out the memory allocated for the object’s properties by setting them to zero. This avoids the usual problem of memory containing garbage from whatever was stored before, but is not enough to initialize an object completely.

For a more detailed response including how this does not apply for malloc, please see the accepted answer for the post https://stackoverflow.com/a/990826/2668545

Community
  • 1
  • 1
ThinkBonobo
  • 15,487
  • 9
  • 65
  • 80
-3

It is in default 0. I think you set it to wrong.

kkocabiyik
  • 4,246
  • 7
  • 30
  • 40