关于Objective-C 的property,很多iOS开发的新手都会很迷惑,也会包括有经验的iOS开发程序员,

因为Objective-C的property,说多不多,说少却也不少,从MRR(Manual Retain Release )到ARC模式,很多属性功能类似

名称却不一样,比如strony和retain,而且又牵扯到release, autorelease, alloc ,new,copy等一众函数,

所以看着很容被绕进去,迷失在这众多的property,

今天特地梳理支持ARC(iOS 5+) 的propterty的关键词:

strong, weak, copy, readonly/readwrite, atomic/nonatomic,assign,retain

由于strong和retain功能相同,所以会在最后总结的时候,比较所有的这些关键词异同点

1:定义一个property

如下,我们定义一个car 的interface, 该属性有一个property 为 brand(品牌)

// Car.h
#import <Foundation/Foundation.h> @interface Car : NSObject @property NSString *brand; @end
//  Car.m

#import "Car.h"

@implementation car

@synthesize brand = _brand;

@end

2:属性的getter 和setter方法和synthesize

编译器会默认的为属性生成getter 和setter方法

- (NSString *)brand
{
return _brand;//_brand即使synthesize指定的属性名称
} - (void)setBrand:(NSString *)brand
{
_brand = brand;
}

注意:synthesize 不是必须明确声明,除非手动些属性的getter和setter方法

否则,complier默认生成的code 如下格式

@synthesize brand = _brand

synthesize关键字缺省方式是:将brand属性对应的实例便令声明为_brand,即_ + propertyname

当然可以自己指定比如brand = xxxbrand

编译器默认会将getter方法和属性同名,setter方法为set+属性(首字母大写),例如setBrand

可以指定属性的getter和setter方法名称

@property (nonatomic,getter=getBrand, setter = setBrand:)NSString *brand;

3:readonly和readwrite

声明 readonly属性

@property (readonly,getter=getBrand)NSString *brand;

声明了readonly的属性,一定没有setter方法,所以你可以使用getter或者 dot方法 获取属性的值,但肯定不可以使用

setter方法修改

Car *c = [[Car alloc]init];0

[c setBrand:@"tony"]; //Error

NSLog(@"%@", [c getBrand]);

声明为readonly 不意味着我们不可以修改,propery 的accessor method 本来就是提供给其他接口调用的,

在我们内部,是直接操纵_brand实例的, 如下

// Car.h
- (void)setBrand:(NSString *)brand;
// Car.m
- (void )setBrand:(NSString *)brand;
{
_brand = brand;
}

readonly 对应的readwrite 属性, readwrite 是default的behavior,可以不显示声明

@property (readwrite)NSString *brand;

4:atomic, nonatomic

atomic 原子的,default behavior,支持多线程操作, 代价是开销比nonatomic大

如果声明一个属性,确定不会运行在多线程的环境,可以直接声明为nonatomic

@property (nonatomic)NSString *brand;

内存管理

Ojective-C 内存模型中,不管是MRR,还是ARC,都是根据对象的引用计数来确定对象是否回收

当对象的 引用计数为0,就会被回收(不一定是立即回收)

从引用计数的原理出发,Objective-C 提出了三种相关的是属性

strong, weak, copy

1:strony 属性

strong属性,即声明一个对象拥有另外一个对象,引用计数 + 1

加入 A对象 有个strong 属性的实例对象B, 则在A对象释放之前,B是不会释放的

看如下sample code

声明一个类Person,Person有一个属性name

//
// Person.h #import <Foundation/Foundation.h> @interface Person : NSObject @property (nonatomic) NSString *name; @end
//  Person.m
#import "Person.h" @implementation Person - (NSString *)description
{
return self.name;
}
@end

声明一个Car 类,有两个属性 model和driver

//  Car.h

#import <Foundation/Foundation.h>
#import "Person.h" @interface Car : NSObject @property (nonatomic) NSString *model;
@property (nonatomic,strong) Person *driver; @end

main.m

// main.m
#import <Foundation/Foundation.h>
#import "Car.h"
#import "Person.h" int main(int argc, const char * argv[]) {
@autoreleasepool {
Person *john = [[Person alloc] init];
john.name = @"John"; Car *honda = [[Car alloc] init];
honda.model = @"Honda Civic";
honda.driver = john; NSLog(@"%@ is driving the %@", honda.driver, honda.model);
}
return ;
}

可以看到,hoda对象对driver对象负责

2:weak属性

strong 属性,很直观的显示对象直接的关系,但也很容易引起内存泄露,

看如下代码,我们稍微小改了Person.h ,增加了Car 属性,

// Person.h
#import <Foundation/Foundation.h> @class Car; @interface Person : NSObject @property (nonatomic) NSString *name;
@property (nonatomic, strong) Car *car; @end

则在main.m

增加一行

john.car = honda;

则此时,john和hoda互相持有对方

二者这件形成了 retain cycle(互相持有的循环),就是典型的内存泄露的一种情况

如果car声明为weak,这个问题即迎刃而解

@property (nonatomic, weak) Car *car;

3:copy 属性

copy不同于strong, 并不拥有copy的对象,而是复制该对象(必须conform NSCopying protocol )

sample code

#import <Foundation/Foundation.h>
#import "Car.h"
#import "Person.h" int main(int argc, char *argv[])
{ Car *bmw = [[Car alloc]init]; Person *driver = [[Person alloc]init]; NSMutableString *name = [NSMutableString stringWithFormat:@"zhangsan"];//mutable 的name 为zhangsan [driver setName:name];
[name setString:@"lisi"];//修改为lisi
[driver setCar:bmw]; [bmw setModel:@"X5"];
[bmw setDriver:driver]; NSLog(@"%@", [driver name]);//仍然是zhangsan }

copy 属性在被赋值的时候就copy了该值,所以即使该值是mutable的,属性的值也不会被修改,

现对于strong的持有对象,copy特别适合只是简单存储值得属性

以上都是ARC支持的属性。

4:属性retain  

 等同于 strong

5:unsafe_unretained

类似于weak,和weak不同的是,如果weak 属性指向的对象如果被销毁后,weak 属性被置为nil,

而 unsafe_unretained 不会,则又可能形成悬垂指针的问题

6:assign

默认的属性,不需要显示声明

指定setter方法进行简单的赋值 ,对基础数据类型(NSInteger,CGFloat)

和C数据类型(int, float, double, char)等等。

 总结:

atomic //default

nonatomic

strong=retain //default

weak

assign //default

unsafe_unretained

copy

readonly

readwrite //default

引用:

http://rypress.com/tutorials/objective-c/properties

http://rypress.com/tutorials/objective-c/memory-management

http://stackoverflow.com/questions/8927727/objective-c-arc-strong-vs-retain-and-weak-vs-assign

Objective-C Properties 详解的更多相关文章

  1. log4j.properties 详解与配置步骤(转)

    找的文章,供参考使用 转自 log4j.properties 详解与配置步骤 一.log4j.properties 的使用详解 1.输出级别的种类 ERROR.WARN.INFO.DEBUGERROR ...

  2. SpringBoot配置文件 application.properties详解

    SpringBoot配置文件 application.properties详解   本文转载:https://www.cnblogs.com/louby/p/8565027.html 阅读过程中若发现 ...

  3. log4j.properties 详解与配置步骤

    一.log4j.properties 的使用详解 1.输出级别的种类 ERROR.WARN.INFO.DEBUGERROR 为严重错误 主要是程序的错误WARN 为一般警告,比如session丢失IN ...

  4. [转]application.properties详解 --springBoot配置文件

    本文转载:http://blog.csdn.net/lpfsuperman/article/details/78287265###; # spring boot application.propert ...

  5. application.properties详解 --springBoot配置文件【转载】

    # spring boot application.properties配置的各个属性详解 # 该示例文件作为标准提供.(官方文档 翻译过来的) # 还是花了些功夫翻译,各位如果转发,请留下本文地址, ...

  6. application.properties详解 --springBoot配置文件

    本文转载:http://blog.csdn.net/lpfsuperman/article/details/78287265###; # spring boot application.propert ...

  7. 转--log4j.properties 详解与配置步骤

    一.log4j.properties 的使用详解 1.输出级别的种类 ERROR.WARN.INFO.DEBUGERROR 为严重错误 主要是程序的错误WARN 为一般警告,比如session丢失IN ...

  8. log4j.properties 详解与配置步骤总结

    先提供一个项目中使用log4j.properties配置 #log4j.rootLogger=WARN, stdout, file log4j.rootLogger=INFO,console,dail ...

  9. 【转】log4j.properties 详解与配置步骤 - edward0830ly的专栏 - 博客频道 - CSDN.NET

    一.log4j.properties 的使用详解 1.输出级别的种类 ERROR.WARN.INFO.DEBUGERROR 为严重错误 主要是程序的错误WARN 为一般警告,比如session丢失IN ...

  10. (转)spring hibernate properties详解

    转载地址:http://blog.sina.com.cn/s/blog_692d0a650100xyqx.html Hibernate配置属性 hibernate.dialect:一个Hibernat ...

随机推荐

  1. python之从文件中按行读取数据

    #!/usr/bin/env python3 # -*- coding: utf-8 -*- __author__ = 'jiangwenwen' # 从文件中按行读取数据 file = open(& ...

  2. 洛谷 P1886 滑动窗口(单调队列)

    题目链接 https://www.luogu.org/problemnew/show/P1886 题目描述 现在有一堆数字共N个数字(N<=10^6),以及一个大小为k的窗口.现在这个从左边开始 ...

  3. Day8---Python的字典类型及操作

    字典类 1.生成方法: a.介绍: 字典是键值对的集合,键值对 : 键是数据索引的扩展 b.生成方法: 使用{}  或者  dict()  a = {'a' = 1, 'b' = 2, 'c' = 3 ...

  4. [fw]Die 為什麼不能用現在完成式?

    have PP是表示"從以前到現在"都直在做的事情 Mr. Chen has taught English for 30 years.---表示teach的動作持續了30年,但Mr ...

  5. python 字符编码问题总结

    都是计算机存储是二进制0101之类的数字 最早计算机在美国开始的 所以数字和英文之类的占用八位 2的8次方 256可以存储对于英文和数字戳戳有余  每个国家都有自己的编码 中国 gb2312 gbk ...

  6. postman 上一个接口的返回值作为下一个接口的入参

    在使用postman做接口测试的时候,在多个接口的测试中,如果需要上一个接口的返回值作为下一个接口的入参,其基本思路是: 1.获取上一个接口的返回值 2.将返回值设置成环境变量或者全局变量 3.设置下 ...

  7. rabbitmq 客户端崩溃退出

    1.创建1个队列 和 创建另1个独占队列 名称相同 即崩溃退出 2..rabbitmq是为了实现实时消息推送的吗?

  8. rabbiitmq非阻塞调用

    https://blog.csdn.net/panxianzhan/article/details/50755409 https://blog.csdn.net/u013946356/article/ ...

  9. HAProxy基于Centos6.5安装及配置

    一.使用2.6内核Linux,配置sysctl参数 vi /etc/sysctl.conf #haproxy confignet.ipv4.tcp_tw_reuse = 1net.ipv4.ip_lo ...

  10. moment.js时间格式化库

    网址:momentjs.cn 主要用来操作时间的格式化.通过发送API请求获取到的数据中:例如[新闻]中的 发布时间,有的时候.请求到的时间,后台没处理过,那么只能前端来操作数据了. moment.j ...