object.variable和object-> variable之间的差异 [英] difference between object.variable and object->variable

查看:31
本文介绍了object.variable和object-> variable之间的差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 object.variable object-> variable 有什么区别?我什么时候应该使用 object-> variable ?

What is the difference in using object.variable and object->variable? When should I use object->variable?

推荐答案

由于使用->"语法(类似于(* obj).var)时,Objective C是C的超集,因此您正在访问实例变量(ivar)就像C结构一样(好吧,ObjC中的类只是花哨的C结构).

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).

因此使用."表示您正在访问媒体资源.属性是在Objective C 2.0中添加的功能,它允许您通过setter/getter方法访问您的ivars,该方法可以自动创建(使用@synthesize),也可以提供自己的实现.顺便说一句,属性绝对没有必要具有相应的ivar.例如,在@interface中声明:

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

然后在@implementation中使用

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

实际上,您可以在这些方法中做任何您想做的事情.因此使用."只是 [obj setSomeText:@"hello"] 的快捷方式.

Actually you can do whatever you want in those methods. So using '.' is just shortcut for [obj setSomeText: @"hello"].

这篇关于object.variable和object-> variable之间的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆