内存管理(2)

内存管理和点语法
OC内存管理需要使用大量的retain和release操作,点语法可以减少retain和release操作。
编译器对于retain的展开,以遛狗原理为例
@property 展开 (retain属性)
@property (retain)Dog *dog;
展开仍然为:
- (void) setDog: (Dog *) aDog;
- (Dog *) dog;
@synthesize dog = _dog;
展开为:
 - (Dog *) dog
{
     return _dog;
}
- (void) setDog: (Dog *) aDog
{
     if (_dog != aDog)
     {
          [_dog release];//如果_dog为空,不会产生错误。
          _dog = [aDog retain];//让计数器加1
     }

- (void) dealloc    //注意dealloc需要更改
{
     self.dog = nil;
     [super dealloc];

copy属性
copy属性是完全把对象拷贝了一份,计数器从新设为1,与原来的数据完全脱离关系。
copy属性的展开
@property  (copy)  NSString *str;
展开为:
getter函数:
-(NSString *)str
{
     return str;
}
setter函数:
-(void) setStr: (NSString* ) newStr
{
     str = [newStr copy];
}

了解NSMutabArray的实现
现在学习写自己的MyArray:
MyArray.h
@interface MyArray: NSObject
{
     NSUInteger _count;
     id _objs[512];
}
@property (retain, readonly) NSUInteger count;
- (void) addObject: (id) object;
- (id) objectAtIndex:(NSInteger) index;
- (void) removeObjectAtIndex: (NSInteger) index;
- (void) removeAll;

@end
MyArray.m
#import “Foundation/Foundation.h”
@implemation MyArray
@synthesize count = _count;
- (id) init
{
     self = [super init];
     if (self)
     {
          _count = 0;
     }
     return self;
}
- (void) addObject: (id) object
{
     if (_count >512)
          return;
     _objs[count] = [object retain];
     _count++;
}
- (id) objectAtIndex:(NSInteger) index
{
     return _objs[index];
}
- (void) removeObjectAtIndex: (NSInteger) index
{
     id obj = objs[index];
     [obj release];
     objs[index] = nil;
}
- (void) removeAll
{
     for (int i  = 0; i < _count; i++)
          [self removeObjectAtIndex:i];
}
- (void) dealloc
{
     [self removeAll];
     [super dealloc];
}
@end
main.m中使用该数组的部分代码:
MyArray * array = [[MyArray alloc]init];
for (int i = 0; i < 4; i++)
{
     Dog *d = [[Dog alloc] init];
     [s setID: i];
     NSLog(@“dog retainCount is %ld”, [d retainCount]);
     [array addObject: d];
     NSLog(@“dog retainCount2 is %ld”, [d retainCount]);
     [d release];
}
[array release];
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值