Reputation: 451
This code is taken from Apples documentation on Storing Preferences in iCloud:
NSInteger reason = -1;
reason = [reasonForChange integerValue];
if ((reason == NSUbiquitousKeyValueStoreServerChange) ||
(reason == NSUbiquitousKeyValueStoreInitialSyncChange)) {
...
What is the reason for declaring reason
as a non-nil value?
What is wrong with directly declaring the NSInteger
from the integerValue
call?
NSInteger = [reasonForChange integerValue];
if ((reason == NSUbiquitousKeyValueStoreServerChange) ||
(reason == NSUbiquitousKeyValueStoreInitialSyncChange)) {
...
It seems to be a different situation but if I need to declare a something outside of the scope it will be set I normally do something like this:
NSInteger reason;
if (something) {
reason = [reasonForChange integerValue];
}
Is that incorrect? Is it something to do with it being an NSInteger
? What am I missing?
Upvotes: 0
Views: 68
Reputation: 4825
You you observe possible values for reason default value 0 is also possible value. Please check enum below
NS_ENUM(NSInteger) {
NSUbiquitousKeyValueStoreServerChange NS_ENUM_AVAILABLE(10_7, 5_0),
NSUbiquitousKeyValueStoreInitialSyncChange NS_ENUM_AVAILABLE(10_7, 5_0),
NSUbiquitousKeyValueStoreQuotaViolationChange NS_ENUM_AVAILABLE(10_7, 5_0),
NSUbiquitousKeyValueStoreAccountChange NS_ENUM_AVAILABLE(10_8, 6_0)
};
If you write something like this
NSInteger reason;
if (something) {
reason = [reasonForChange integerValue];
}
Even if something is false the following if condition will succeed.
if ((reason == NSUbiquitousKeyValueStoreServerChange) ||
(reason == NSUbiquitousKeyValueStoreInitialSyncChange)) {
...
There for you have to initiate as
NSInteger reason = -1;
Upvotes: 1
Reputation: 726809
What is the reason for declaring
reason
as a non-nil value?
There is no point in doing that. A shorter declaration/initialization that you show below, i.e.
NSInteger reason = [reasonForChange integerValue];
would work just fine, because there is no code path that leaves reason
unchanged. In other words, the -1
value assigned on initialization is never read by the program, making the assignment unnecessary.
if I need to declare a something outside of the scope it will be set I normally do something like this:
NSInteger reason; if (something) { reason = [reasonForChange integerValue]; }
Is that incorrect?
Yes, that would be incorrect, because when something
evaluates to NO
, the value of reason
remains uninitialized. In this situation you should provide reason
with an initial value, because reading an uninitialized local variable is undefined behavior.
Upvotes: 1