OC-025.OC手动MRC内存管理@property的使用方法

为了简化程序员所需输入的代码,编译器同样提供了@property内存管理的方法

手动内存管理的关键字

1.当属性是一个普通OC对象的时候,使用retain

retain:会在setter 和 getter方法中加入一些内存管理的代码

2.当属性是一个基本数据类型的时候,使用assign

assign 直接赋值,不生成内存管理代码

3.copy 复制对象,NSString 使用copy

线程安全
4.nonatomic:非原子,不会生成线程安全的代码,速度快,iOS通常都是这种
5.atomic:原子(默认),会生成线程安全的代码,速度慢

控制权限
6.readwrite:可读可写,生成getter 与 setter方法是声明与实现
7.readonly:只读 只生成getter方法

修改方法名称
8.getter 修改生成的getter方法的名称一般情况下,BOOL类型的属性的getter方法是以is开头的
9.setter 修改生成的setter方法的名称,需要加冒号,不能在点语法中显示,一般不去修改它

#import <Foundation/Foundation.h>//------main
#import "LSPerson.h"
int main(int argc, const char * argv[]) {
    //注意内存管理的黄金法则:有加必有减
    LSPerson *per =[[LSPerson alloc] init];
    LSIpad *ipad1 = [[LSIpad alloc] init];
    per.ipad = ipad1;
    [ipad1 release];
    LSIpad *ipad2 = [[LSIpad alloc] init];
    per.ipad = ipad2;
    [ipad2 release];
    [per release];
    ipad1 = nil;   //如果下面还有很多代码,如果不在使用这些指针,请清空他们
    ipad2 = nil;
    per = nil;
    
    [per setManNew:YES];    //证明setter是可以修改setter的方法名的,记得加冒号:
    BOOL isMan = per.isMan; //证明getter是可以修改getter的方法名的
    NSLog(@"%d",isMan);
    return 0;
}
#import <Foundation/Foundation.h>//------LSPerson.h
#import "LSIpad.h"
@interface LSPerson : NSObject
@property (nonatomic,retain)LSIpad *ipad;//OC对象用retain
@property (nonatomic,assign,readonly) int age;//基本数据类型用assign
@property (nonatomic,copy) NSString *name;//nsstring用copy
@property (nonatomic,assign,getter=isMan,setter=setManNew:) BOOL Man;//set方法需加:
@end
#import "LSPerson.h"//------LSperson.m

@implementation LSPerson

-(void)dealloc{   //为了验证而写
//    [_ipad release];//如果不加release那么人回收了,ipad还在,造成内存泄露
//    _ipad = nil;
    self.ipad = nil; //等价与上面2句,self。ipad会进入set方法,先release,再nil
    self.name = nil;
    NSLog(@"%s",__func__);
    [super dealloc];
}

@end
#import <Foundation/Foundation.h>//------LSIpad.h

@interface LSIpad : NSObject

@end
#import "LSIpad.h"//------LSIpad.m

@implementation LSIpad
-(void)dealloc{
    NSLog(@"%s",__func__);
    [super dealloc];
}

@end







  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值