Reputation: 40
My question is how to pass Null values in to NSMutableArray/NSArray.
But by searching google and going through different sites, i think that i have achieved my purpose. But, while trying i got a new doubt.
See the below code to understand my question
I am declaring a mutable array and initializing it with some objects initially and also i am passing a null in to it at the time of declaration itself.
Now when i run this code below
NSMutableArray * mar = [[NSMutableArray alloc]initWithObjects:@"first",@"last", nil];
[ar addObject:[NSNull null]];
NSLog(@"%@",mar);
The o/p is :
(
first,
last,
"<null>"
)
But my actual doubt is when i initialize the NSMutableArray as below
NSString *str;
NSMutableArray * mar = [[NSMutableArray alloc]initWithObjects:@"first",str,@"last", nil];
[ar addObject:[NSNull null]];
NSLog(@"%@",mar);
The o/p is :
(
first,
"<null>"
)
The 2nd element in the array is "null", i understand that as i have passed a variable without assigning any value to it. It is printing null. But why are the remaining elements not printed.
According to what i know, the array will stop adding elements whenever it overcomes nil while initializing. But here, in this case. The o/p shows that the 2nd element is also null.(But not nil.)
Then why does the remaining elements are not printed.
UPDATING QUESTION
NSString* str;
NSLog(@"%@",str);
NSMutableArray * mar = [[NSMutableArray alloc]initWithObjects:@"first",str,@"last", nil];
NSLog(@"%@",mar);
and the o/p for the above code is
(null) // for str an uninitialised NSString variable.
(
first // first element in the array
)
If the value present in str is (null), how come the array encountered nil and stopped adding elements to array and printing them.
Now, someone answer this?
Upvotes: 0
Views: 1645
Reputation: 467
in objective-C, when iterating through Array if nil/null encountered then it gets treated as end of array.
this is the reason it is not printing remaining values.
in case you want clear diff between nil/null/Nil then check Difference between nil, NIL and, null in Objective-C
Upvotes: -1
Reputation: 130122
initWithObjects
uses nil
as the marker for the last item. If you pass a nil
(the unitialized str
variable) to it as the 2nd item out of 4, only the first one is actually added.
[[NSMutableArray alloc]initWithObjects:@"first",str ?: [NSNull null],@"last", nil];
will fix your problem by replacing the nil
with a [NSNull null]
.
Also see NSArray creation with variable argument lists
Upvotes: 3