objective-C的@property和@synthesize用法

本文探讨了Objective-C与Swift两种编程语言在iOS开发领域的应用与区别,包括其语法特点、性能表现及社区支持等内容,为开发者提供选择语言的参考。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

@property相当于声明

@synthesize相当于实现set方法和get方法

 

比如有一个Student类,在Student.h文件中,原始的声明方法如下:

#import <Foundation/Foundation.h>

@interface Student : NSObject {
    int _age;//默认为protected
}

- (void)setAge:(int)newAge;
- (int)age;

@end

 

一般成员变量的命名为"_"+名字

 

等效的Student.h文件(使用@property)如下:

#import <Foundation/Foundation.h>

@interface Student : NSObject

@property int age;//注意这里是age不是_age

@end

 

 

相应的原始实现方法的Student.m文件为:

#import "Student.h"

@implementation Student

- (int)age {
    return _age;
}

- (void)setAge:(int)newAge {
    _age = newAge;
}

@end

 

等效的Student.m文件(使用@synthesize):

#import "Student.h"

@implementation Student

@synthesize age = _age;

@end

 

不过其实以上的

@synthesize age = _age;

也可以省略,xcode会自动实现。

也就是只需要在Student.h中写好@property的声明,就可以了。xcode会自动设置变量名为:"_"+名字

 

如果要重新实现setter和getter,xcode就不会为你添加@synthesize,那么也就不会自动为你声明变量_age,所以此时就必须在声明文件中添加声明的变量,否则会报错。

比如在setter中添加一句输出:

- (void)setAge:(int)newAge {
    NSLog(@"this is setter.");
    _age = newAge;
}

- (int)age {
    return _age;
}

那么在Student.h中,要添加变量_age的声明:

@interface Student : NSObject {
    int _age;//添加这行
}

@property int age;

@end

 

另外,除了@property和@synthesize实现的基本操作外,还可以添加方法,比如同时设置两个变量的方法:

声明:

@interface Student : NSObject {
    int _age;

    float _height;

}


- (void)setAge:(int)newAge andHeight:(float)newHeight;

@end

实现:

@implementation Student

- (void)setAge:(int)newAge andHeight:(float)newHeight {
    _age = newAge;
    _height = newHeight;
}

@end

基本知识,记录一下!

转载于:https://www.cnblogs.com/xiaovid/p/3535332.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值