OC基础 点语法的使用

1.创建一个Student类继承于NSObject,Student.h文件

#import <Foundation/Foundation.h>

@interface Student : NSObject
{
NSString *_name;
NSString *_nickName;
} //@property定义属性
//1,它给该类声明了一个属性名+下划线的变量
//2,它给该类声明了一个getter方法和一个setter方法 //修饰符
//atomic和nonatomic
//原子性和非原子性,atomic线程安全,nonatomic线程不安全
//一般情况下使用nonatomic //setter修饰符指定赋值时调用哪个方法来实现setter
//setter修饰符指定读取值时调用哪个方法来实现getter
@property (nonatomic,setter = setNickName:,getter = nickName) NSString *nickName; //修饰符
//assign用来修饰基本类的
//strong或者retain是用来修饰对象指针的
//readonly只读:只声明和实现getter,不声明和实现setter方法
//readwrite可读写:声明和实现了getter和setter,默认就是readwrite
@property (assign,readonly) int age;
@property (retain,readwrite) NSString *secondName; -(void)setName:(NSString *)name;
-(NSString *)getName;
-(void)setaaa:(NSString *)aaa; @end

2.Student.m文件

#import "Student.h"

@implementation Student
//@synthesize在.m文件内为属性添加setter和getter方法的实现
//@synthesize nickName; -(void)setName:(NSString *)name
{
_name = name;
} -(NSString *)getName
{
return _name;
} -(void)setNickName:(NSString *)nickName
{
_nickName = nickName;
self.nickName = nickName;
} -(void)setaaa:(NSString *)aaa
{ }

3.创建Teacher类继承于NSObject,Teacher.h文件

#import <Foundation/Foundation.h>
#import "Student.h" @interface Teacher : NSObject @property Student *stu; @end

Teacher.m文件

#import "Teacher.h"

@implementation Teacher

@end

4.点语法的使用

        Student *stu = [[Student alloc] init];
[stu setName:@"zhangsan"];
NSString *name = [stu getName];
NSLog(@"%@",name); //属性名在=的左侧,代表赋值,实际是调用类的setter方法
stu.nickName = @"xiaozhang";
//属性名在=的右侧,代表读取值,实际是调用类的getter方法
NSLog(@"%@",stu.nickName); Teacher *tea = [[Teacher alloc] init];
tea.stu = stu;
05-03 21:30