I want to know height of a view.
NSInteger height = view.frame.size.height;
In above code, frame and size are structure and view is object.
If view is nil in the above code, what value does height return?
I know that I get nil if I send message to nil object.
But size is not object.
When I ran the above code, I get 0 if view is nil.
Does it always return 0, or returning 0 isn’t guaranteed?
Also in the following code, height returns zero.
CGSize size;
NSInteger height = size.height;
In Objective-C, structures which are not initialized always returns zero?
In your first example (
view.frame.size.height), you are guaranteed to get 0 ifviewis nil. This became true in Xcode 4.2 (using clang); for older compiler versions (and gcc I believe) the result is undefined. Source: Greg Parker’s blog.For your second example, it depends on where
CGSize size;is declared. If it’s a local variable like this:then
heightis undefined. It might be zero, or it might be any other number.If it’s an instance variable like this:
then it is guaranteed to be initialized to zero by
+[MyObject alloc].If it’s a global variable like this:
(or a static variable) then it’s guaranteed to be initialized to zero when your app launches.