ios属性修饰符详解

时间:2021-10-04 21:07:27
//
// Person.h
// TEST123
//
// Created by zhengbing on 6/14/16.
// Copyright © 2016 zhengbing. All rights reserved.
//

#import <Foundation/Foundation.h>

@interface Person : NSObject
@property (nonatomic, copy) NSString *copiedString;

@property (nonatomic) NSString *name;           //不会影响被赋值的字符串变量.
@property (nonatomic,strong) NSString *name1;   //和默认效果一样,不会影响被赋值的字符串变量.
@property (nonatomic,weak) NSString *name2;     //和默认效果一样,不会影响被赋值的字符串变量.
@property (nonatomic,retain) NSString *name3;   //和默认效果一样,不会影响被赋值的字符串变量.
@property (nonatomic,assign) NSString *name4;   //和默认效果一样,不会影响被赋值的字符串变量.

@property (nonatomic) NSArray *arr;         //arr 置为 nil 之后,不会影响他赋值的变量值。
@property (nonatomic,strong) NSArray *arr1; //和 arr 一样,说明默认为strong。
@property (nonatomic,weak) NSArray *arr2;   //会被警告,arr 置为 nil 后,被赋值的变量也会为(null)。
@property (nonatomic,retain) NSArray *arr3; //和 strong 一样。
@property (nonatomic,assign) NSArray *arr4; //assign 简单赋值,不更改引用计数.

@end



//
// main.m
// TEST123
//
// Created by zhengbing on 6/14/16.
// Copyright © 2016 zhengbing. All rights reserved.
//

#import <Foundation/Foundation.h>
#import "Person.h"


int main(int argc, const char * argv[]) {
    @autoreleasepool {
        // insert code here...


        Person *per = [[Person alloc] init];

        per.name = @"zhangsan";
        per.copiedString = @"copiedString";
        per.arr = @[@1,@2,@3];

// NSString *otherName = per.name;
// per.name = nil;
// 
// NSLog(@"%@",otherName);

        __strong NSArray *strongArr = per.arr;
        per.arr = nil;
        NSLog(@"strongArr:%@",strongArr);

        __weak NSArray *weakArr = strongArr;
        strongArr = nil;
        NSLog(@"weakArr:%@",weakArr);

/* __strong 修饰变量,相当于强引用,引用计数会加一,也就是赋值给他的变量为 nil 了,他也不会释放。 __weak 修饰变量,相当于弱引用,引用计数不会加一,也就是赋值给他的变量为 nil 了,他也会被释放,并置空 (null) */

    }
    return 0;
}

2016-06-14 21:22:44.794 TEST123[11421:146417] otherArr:(
    1,
    2,
    3
)
2016-06-14 21:22:44.796 TEST123[11421:146417] strongArr:(null)
Program ended with exit code: 0