从今天开始学习ios,入门第一天(Object-C学习笔记)自动引用计数和为类添加属性

本文介绍了Objective-C中属性的概念,如何为类添加属性,并详细解释了如何使用@synthesize声明私有变量、实例变量和属性。此外,文章还讨论了强引用(strong)和弱引用(weak)的区别及在现代Objective-C中的应用。

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

1.Clang静态分析工具

使用ARC机制已经成为了Mac和ios开发者的基本练习,使用ARC的最大好处就是初学者不用再为内存管理的诸多问题而担心了,不过这并不代表你不需要知道对象在内存中的存储机制。

2.为类添加属性

在所有的程序开发语言中,都不建议直接定义公共实例变量,常见的方法是将这些实例变量设为私有变量,通过getter和setter方法对其进行操作。

Object-C的方法是一种类似于Java和C#想结合的方法。与C#相同,Object-C有属性的概念,不过也有java语言的getter和setter方法的具体实现代码。

//in the simpleClass.h file
@interface SimpleClass : NSObject
{ int _firstInt;
  int _secondInt;
}
@property int firstInt;
@property int secondInt;
@end
//in the SimpleClass.m file
@inplementation SimpleClass
- (void)setFirstInt : (int)firstInt
{
  _firstInt =firstInt;
}
- (int)firstInt
{
return -firstInt;
}
- (void)setSecondInt : (int) secondInt
{
  _secondInt =secondInt;
}
- (int)secondInt
{
  return _secondInt;
}
@end
SimpleClass *simpleClassInstance=[ [SimpleClass alloc] init];
[simpleClassInstance setFirstInt:1];
[simpleClassInstance setSecondInt:2];
int firstIntValue = [simpleClassInstance firstInt];
3.使用@synthesize声明私有变量,实例变量和属性的命名类似,不同之处在于实例变量要带一个下划线。

//in the SimpleClass : NSObject
@property int firstInt;
@property int secondInt;
- (int)sum;
@end
//in the SimpleClass.m file
@implementation SimpleClass
- (int)sum
{
retun -firstInt+_secondInt;
}
@end
4.点注法

将 int firstIntValue = [SimpleClassInstance firstInt];

改为:int firstIntValue= simpleClassInstance.firstInt;

5.现代Object-C中的Strong和Weak属性

//in the SimpleClass.h file
@interface SimpleClass : NSObject
@property (atomic,strong) SecondClass *aSecondClassInstance;//原子特性,保证当程序异步访问多个线程时其数据的读取和设置都是一定能完全执行的,防止在写入未完成                                                          //的时候被另外一个线程读取。非原子性不能保证这一点。然而使用atomic属性是有限制的。
                                                             //因为有其他方法可以提供同样的保障,大部分情况下都声明属性为nonatomic以避免额外的开销。
@property(nonatomic,weak) SecondClass *anotherSecondClassInstance;
@end

如果一个对象的属性中声明了其为strong,则只要有内容指向该对象,就不会被释放,这其实暗示着你的对象拥有其他对象。

如果对象的属性声明为weak,意味只要有一些其他对象有strong指针指向其时,他仍然保存在内存中。(weak属性用户避免强引用循环)





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值