OC中几种定义类属性的区别(包括在分类中的实现)

2019-03-27  本文已影响0人  你duck不必呀

第一种,直接写@interface...@end在大括号里面

在.h文件

@interface testClass :NSObject
{
/*默认是protected,要在外界访问需要加public修饰*/
    @public
    NSInteger age;
    NSString *name;
}
@end

在外界调用:

{
testClass *test=[testClass new];
/*调用和C语言的结构体类似(如下),不能用点语法*/
test->age=18;//或(*test).age=18;
test->name=@"苍老师";//或(*test).name=@"苍老师";
NSLog(@"%@,%@",test->age,test->name);
}

在本类调用

{
/*调用和C语言的结构体类似(如下),不能用点语法,self代表当前类对象(testClass *)*/
self->age=18;
self->name=@"苍老师";
//或
(*self).age=18;
 (*self).name=@"苍老师";
NSLog(@"%@,%@",test->age,test->name);
}

在.m文件

@interface testClass()
/*默认是private,无法修改*/
    @public//无效
    NSInteger age;
    NSString *name;
@end

在外界不能访问,本类和在.h文件一样

{
/*调用和C语言的结构体类似(如下),不能用点语法,self代表当前类对象(testClass *)*/
self->age=18;
self->name=@"苍老师";
//或
(*self).age=18;
 (*self).name=@"苍老师";
NSLog(@"%@,%@",test->age,test->name);
}

第二种 通过@property定义

在.h文件

@interface testClass :NSObject
/*默认是private*/
@property NSInteger age;
@property NSString *name;
@end

在外界访问

{
/*只能用.语法*/
testClass *test=[testClass new];
test.age=18;
test.name=@"苍老师";
}

在本类访问

{
self.age=18;//或 _age=18
 NSLog(@"%@",self.age);
}

@property关键字在此处做了以下事情

  1. 在.h文件里面用大括号创建了带_前缀的同名变量,默认private修饰
    2.在.h文件声明对应的getter和setter方法,并在.m文件实现

验证一下

/*在.h文件中只用@property 定义属性*/
@interface testClass :NSObject
/*默认是private*/
@property NSInteger age;
@property NSString *name;
@end

在外界能通过.语法访问

testClass *test=[testClass new];
test.age=18;

因为在.h文件的属性能在外界访问,

在本类

{
    self.age;
    self.name;
    self->_age;
    self->_name;
    (*self)._age;
    (*self)._name;
}

所以有带_的同名变量在.h文件

在类别中也可以添加属性,在.h文件

@interface testClass (sex)
@property (nonatomic, strong) NSString *sex;
@end

在.m中手动实现get,set,在用到_sex时,编译器均提示未定义的成员属性。

@implementation testClass (sex)

- (void)setSex:(NSString *)sex{
    _sex=sex;//Use of undeclared identifier '_sex'; did you mean 'sex'?
    
}

- (NSString *)sex{
    
    return _sex;//Use of undeclared identifier '_sex'
}

所以添加的sex属性,没有生成_sex成员变量,没有get和set方法

 testClass *test=[[testClass alloc]init];
        test.name=@"高松惠理";
        test.age=@"26";
        test.sex=@"女";//xcode能提示
        
        NSLog(@"name=%@,age=%@,sex=%@",test.name,test.age,test.sex);

xcode能提示,但是一运行会出错,没有set,get方法
要用的话,可以通过运行时实现

#import "testClass+sex.h"
#import <objc/runtime.h>

@implementation testClass (sex)

- (void)setSex:(NSString *)sex{
    objc_setAssociatedObject(self, @"sex", sex, OBJC_ASSOCIATION_COPY_NONATOMIC);
    
}

- (NSString *)sex{
    
  return objc_getAssociatedObject(self, @"sex");
    
}
@end

最后运行结果
name=高松惠理,age=26,sex=女

上一篇 下一篇

猜你喜欢

热点阅读