您的位置:首页 > 移动开发 > Objective-C

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

2015-11-29 13:27 846 查看
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属性用户避免强引用循环)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  ios 入门 笔记