第一天学习Objective-C但是有一个java背景。我想为我的实例变量使用与我的参数相同的变量名。在java中我们这样做
public class Person
{
private String name;
private String age;
public void setName(String name)
{
this.name = name;
}
public void setAge(String age)
{
this.age = age;
}
}
目标c到目前为止我有这个
@interface Person : NSObject
{
int age;
int name;
}
-(void) setAge:(int) age;
-(void) setName:(int) name;
-(int) getAge;
-(int) getName;
@end
@implementation Person
-(void) setName:(int) w
{
weight = w;
}
-(void) setAge:(int) a
{
age = a;
}
-(int) getName
{
return name;
}
-(int) getAge
{
return age;
}
@end
答案 0 :(得分:1)
Objective-C程序员不喜欢打字,所以我们这样做:
@interface Person : NSObject
@property(nonatomic, copy) NSString *name;
@property(nonatomic, assign) int age;
@end
@implementation Person
@end
您可能需要先阅读Apple的Objective-C Programming Language introduction。
答案 1 :(得分:1)
在Objective-C中,您可以定义自己的访问者或使用@syntehsize
自动为您创建访问者。
如果您想手动定义访问者,则设置setter如下:
- (void)setName:(NSString *)name {
self.name = name;
}
- (void)setAge:(NSInteger)age {
self.age = age;
}
对于getter,您只需按如下方式声明它们:
- (NSString *)name {
return self.name;
}
- (NSInteger)age {
return self.age;
}
答案 2 :(得分:0)
答案 3 :(得分:0)
你在ObjectiveC中有这个,因为你正在使用C样式变量。如果将变量声明为ObjectiveC属性并使用正确的合成指令:
@property (int) age;
@synthesize age;
然后你可以通过self.age
self.age = age;
在实现文件中。这将在内部调用-(void)setAge:(int)age
方法和将自动定义的-(int) age
方法。
最后因为ObjectiveC对象只是一个指向C结构的指针,所以你可以通过使用语法来引用指向结构的指针的字段来跳过ObjectiveC来访问变量:self->age = age