问题
From what I understand (and please correct me if I'm wrong):
int x, count = 10;
int *hello;
hello = &count;
x = *hello;
Here the variables x and count are declared to be of type integer. Additionally, the variable count is assigned the value of 10.
hello is a pointer to type integer. hello is then assigned the address of count. In order to access the value of count, hello must have an asterisk in front of it, ie, *hello.
So, x is assigned the value of whatever is in count and in this case, 10.
However...
Fraction *myFraction = [[Fraction alloc] init];
[myFraction someMethod];
Here, if I understand correctly, myFraction is a pointer to an instance of Fraction class.
myFraction is pointing to (or rather assigned the address of) an object which has been assigned memory and initialised.
Surely, in order to access the object that myFraction points to, I ought to write:
[*myFraction someMethod];
Given the way in which x accessed the value of count, surely in order to access the object, one ought to write this and not:
[myFraction someMethod];
In addition, if I have
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSString *str = @"Programming can be a headache";
NSLog (@"%@\n", str);
Why is str being treated as an object above? Or is str an object and in which case, why would I want to make it point to an instance of NSString class? Surely, I ought to be able to just assign an object to str?
回答1:
All the usage of objects in objective c is done through object references, e.g. pointers.
- The Objective C syntax lets you treat objects without dereferencing them, this is different than C / C++ for that matter.
str
is an object reference of typeNSString
(asmyFraction
) and@"Programming can be a headache"
is an object reference of typeNSString
as well, so you can assign it tostr
.
回答2:
Additional to Binyamin
- Everything inside the brackets [ ] is objective-C and not simple C (so [*object message] is not common to use)
- [object message], you send the "message" to your object, and the object responds with something (he can return something or he can do something without anything in return).
- Everything with a * on the left is pointer. So *str is a pointer. And where is it point? to an object NSString. The @"blabla" returns the adress of one CONSTANT string that has generated directly by the compiler.
- NSLog (@"%@\n", str); here the %@ calls the +Description class method of NSString object called str. By default the description of an NSString Object returns the value of the string (the text). %@ is not a simple replace like the %d with numbers (int,double etc). All objects have +Description method that inherit from the NSObject (note is Class method and not instant).
description
Returns a string that represents the contents of the receiving class.
- (NSString *)description
来源:https://stackoverflow.com/questions/10461125/pointers-on-objective-c