What is the difference 开发者_如何学运维in using object.variable
and object->variable
? When should I use object->variable
?
As Objective C is a superset of C when using '->' syntax (which is similar to (*obj).var) you are accessing the instance variable (ivar) like in C-structure (well, classes in ObjC are just fancy C-structures).
Thus using the '.' implies that you're accessing the property. Properties is the feature that was added in Objective C 2.0 and allows you access your ivars via setter/getter methods, that could be created automatically (using @synthesize) or you can provide your own implementation. BTW it is absolutely not necessary for properties to have corresponding ivar. For example in @interface you declare:
@interface Ololo : NSObject {
//NOTE: there is no ivar named someText or _someText or whatever you want
}
@property(nonatomic) NSString* someText;
@end
Then in @implementation:
@implementation Ololo
@dynamic someText; //we're using this to tell compiler that we will provide getters/setters ourselves and it doesn't need to generate them (though it is not necessary to do that)
-(NSString*) someText {
return [NSString stringWithContentsOfFile: @"some_file_path"]; //we actually get value from file
}
-(void) setSomeText:(NSString*) str {
[@"asdas" writeToFile: @"some_file_path" atomically: YES];
}
@end
Actually you can do whatever you want in those methods. So using '.' is just shortcut for [obj setSomeText: @"hello"]
.
If you use . you are accessing a property of the class which you defined using @property and created with @synthesize. If you use -> you just access an instance variable, but its not really something you should use a lot. And the use is very limited. So don't make it difficult for yourself and use properties with .
The indirection operator (->) is inherited from C and can be used as a shorthand for accessing fields in a structure, to which you have a pointer.
As an example...
typedef struct IPhone {
int serialId;
} IPhone;
Here I have a traditional C struct which I can instantiate as follows...
IPhone *phone = (IPhone*)malloc(sizeof(IPhone));
Now to access its fields I can either do it the long way...
*(phone).serialId = 1123432324;
Or I can use the shorthand indirection operator...
phone->serialiId = 1123432324;
At the heart of every ObjectiveC class is a C struct. So what you're doing when you use the indirection operator is to jump back to old C syntax to backdoor into the underlying representation. It works, but it's not the prescribed ObjectiveC way.
object->variable is direct access to the variable. object.variable is a method call to the getter accessor method '-(id)variable'or setter accessor method '-(void)setVariable:(id)value' depending on context. You must write the accessor methods yourself or use @synthesize to generate them in order to use dot syntax.
Good programming practice dictates you always use accessor methods to access an instance variable from another instance. ie, dont use ->
精彩评论