PDA

View Full Version : [NOOB] Question about asterisk placement in Obj C




swiftd
Jul 12, 2009, 08:54 PM
Hey guys,

I'm currently learning Objective C and have a question about asterisk placement (I generally understand pointers using asterisks to declare them). In the book I'm reading (iPhone Development for Dummies) the asterisk is placed differently a few times, and I'm not sure why. Could someone tell me why it's in different locations in the following examples?

NSString* blah
(NSString *) blah
IBOutlet UITextfield *textField

And also why there is no asterisk in the following statement?

CGRect rect = self.view.frame;

Thanks for reading!



lee1210
Jul 12, 2009, 09:04 PM
In not the order you asked:
CGRect is a structure, and that's a local instance. You can have pointers to structures on the heap or local instances, though in Foundation most struct *s are typedef'd to TypeRef (i.e. CGRectRef) so you don't have *s about when dealing with structures, to delineate from Objects.
http://developer.apple.com/DOCUMENTATION/GraphicsImaging/Reference/CGGeometry/Reference/reference.html#//apple_ref/doc/uid/TP30000955-CH2g-C016213

NSString* blah
IBOutlet UITextfield *textField

These two just show a difference in style. I prefer that the * go with the varaible like the second example, for this reason:

int *x,y,z,a;

in this case, if you put the * next to int, it might mislead one into thinking everything is an int *, instead of x being an int * and y,z, and a being ints.

(NSString *) blah
In this case, i would expect to see this in the signature of a class or object method. In this case, the types are always parenthesized. If you saw this in another context, that would be odd.

-Lee

allegrocm
Jul 13, 2009, 02:27 AM
(NSString*) blah

could also be casting blah from another pointer type, such as NSObject, to an NSString pointer.

ken

lee1210
Jul 13, 2009, 07:59 AM
(NSString*) blah

could also be casting blah from another pointer type, such as NSObject, to an NSString pointer.

ken

Good call, out of context it was hard to place.

-Lee

Cromulent
Jul 13, 2009, 08:30 AM
An important thing to remember when programming in Objective-C (and most other languages) is that whitespace is meaningless. All you need to do is make sure that keywords are kept together. int and in t are different for instance.

int* x;
int * x;
int *x;
int*x;

are all exactly the same. I could write it as:

int * x ;

if I wanted and it would still be fine.