Objective-C 中的 @property 和 @synthesize 与 Ruby 编程语言中的 attr_accessible 相同吗?

发布于 2024-12-01 03:58:48 字数 143 浏览 3 评论 0原文

我可以在 Objective-C 中使用 @property 和 @synthesize ,这样我就不必编写 getter 和 setter 方法。在我看来,Ruby 中有 attr_accessible 做着同样的事情。我是对的还是有一点区别?

I can use @property and @synthesize in Objective-C so i do not have to write getter and setter methods. In Ruby there is the attr_accessible doing the same in my opinion. Am i right or is there a little difference?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

葬花如无物 2024-12-08 03:58:48

从基本术语来说,是的,

@synthesize 可以节省您编写方法的时间。

您也可以使用@dynamic,然后自己实现它们。

in basic terms YES

the @synthesize is the one saves you writing the methods

You can also use @dynamic and then implement them yourself.

晚风撩人 2024-12-08 03:58:48

你几乎是对的(tm)。可能唯一的偏差是使用 readonly 修饰符声明 @property 会导致 ruby​​ 中的 attr_reader 。虽然 ruby​​ 有 attr_writer,但 Objective-C 中没有 writeonly 属性。

You are almost right (tm). Probably only deviation is that declaring @property with readonly modifier would result in attr_reader in ruby. And while ruby has attr_writer there is no such thing as writeonly property in Objective-C.

一抹苦笑 2024-12-08 03:58:48

基本上是的,这是同一件事:
在 ruby​​ 中,您有 arr_accessible 方法,它为您创建 getter 和 setter。
在 Objective-C 中,@property 在 .m 文件中直接创建 getter 和 setter。
示例:

@interface MaClasse : NSObject {
  int myVariable;
}

@property(nonatomic, assign) int myVariable;
@end

添加 @property 与创建相同:

-(int)myVariable {
  return myVariable;
}

并且

-(void)setMyVariable:(int)newValue {
  myVariable = newValue;
}

可以通过在 .m 文件中添加 @synthetize myVariable 来添加此方法。

在 ruby​​ 中,您只需执行以下操作

class MyClass
  attr_accessor :my_variable 
end

attr_accessor :my_variable 相当于:

def my_variable
  @my_variable
end

def my_variable=(my_variable)
  @my_variable = my_variable
end

Basicly yeah, it the same thing :
In ruby you've got the arr_accessible method, who create for you getter and setters.
in objective-c, @property creates directly getter and setter in your .m file.
example :

@interface MaClasse : NSObject {
  int myVariable;
}

@property(nonatomic, assign) int myVariable;
@end

adding the @property is the same think as creating:

-(int)myVariable {
  return myVariable;
}

and

-(void)setMyVariable:(int)newValue {
  myVariable = newValue;
}

you add this methods by adding @synthetize myVariable in your .m file.

in ruby, you just have basicly to do this

class MyClass
  attr_accessor :my_variable 
end

attr_accessor :my_variable is equivalent to this:

def my_variable
  @my_variable
end

def my_variable=(my_variable)
  @my_variable = my_variable
end
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文