I am learning how to create iPhone apps and I have seen that most of the variables we create store memory addresses (pointers) instead than holding the actual value or object. I also have found out that every time you declare a variable with the pointer char (*
) you know that the variable is going to hold the address and whenever you don't use the (*
) mark to declare a variable you know that it will hold the value instead than the memory location. But I don't know when to us which. for example I have:
CGFloat someVar = [image1 alpha]; // This variable does not require *
// image 1 is a: IBOutlet UIImageView
and in this o开发者_Python百科ther case I have to use a pointer:
UIViewController *someOtherVar = [[UIViewController alloc] init]; // this type of var requires *
It will be nice if I can know when can I use each instead of trying each until project compiles.
The function and method signatures in the headers and documentation will indicate what the type is.
For example, here is how the alpha
property is declared for UIView
:
@property(nonatomic) CGFloat alpha;
There is no *
anywhere, so you know it returns CGFloat
and not CGFloat*
.
In contrast, the backgroundColor
property is declared like this:
@property(nonatomic, copy) UIColor *backgroundColor;
so you know it will return UIColor*
(a pointer).
Some things are declared with a type of id
, which is always going to be a pointer to an object.
In general, Objective-C objects (types declared with @interface
) will always be referenced as pointers, while primitive C types and structs
will often (but not always) be passed and returned by value.
Oversimplifying greatly, but it depends on the data being returned.
From your examples, CGFloat
is a wrapper for float
, which is a primitive C data type. [image1 alpha]
returns a CGFloat
. UIViewController
is an object type. [[UIViewController alloc] init]
returns a pointer to this allocated memory, (UIViewController *)
. Therefore you need to use the pointer.
Pointers can be used in more cases than can be described. Generally speaking, as you are starting out, you typically use pointers for objects. But I encourage you to check the documentation to determine the exact data type. It will provide hints as to the data type returned by a specific method or property.
精彩评论