Skip to main content
  1. Objective-C/

Keywords

·1 分钟
OC STRONG WEAK Copy
Objc - 系列文章之一
Part 1: 当前阅读

strong / weak / copy(ARC环境)

Automatic Reference Counting (ARC) is a compiler feature that provides automatic memory management of Objective-C objects. Rather than having to think about retain and release operations, ARC allows you to concentrate on the interesting code, the object graphs, and the relationships between objects in your application.

Automatic Reference Counting(ARC)技术是用于OC对象的内存管理。即在适当的时候对OC对象retain和release操作。
strong是强引用,会持有对象,引用计数器会+1>

strong是强引用,会持有对象,引用计数器会+1 #

strong是为了告诉编译器(xcode),被strong修饰的对象是强引用,需要retain操作,引用计数器会+1,默认情况下声明变量都是隐式strong申明。

默认情况下strArr引用testArr打印输出


NSArray *testArr = @[@"a", @"b"];
NSArray *strArr = testArr;

testArr = nil;
NSLog(@"print str is %@", strArr);
    
// 打印结果
2021-05-30 15:33:14.931372+0800 Strong&Weak[3480:197342] print str is (
    a,
    b
)

__strong修饰情况下strArr引用testArr打印输出

NSArray *testArr = @[@"a", @"b"];
__strong NSArray * strongStrArr = testArr;

testArr = nil;
NSLog(@"print strongStr is %@", strongStrArr);

// 打印结果
2021-05-30 15:37:30.308564+0800 Strong&Weak[3551:201548] print strongStr is (
    a,
    b
)

__weak修饰情况下strArr引用testArr打印输出

NSArray *testArr = @[@"a", @"b"];
__weak NSArray * weakStrArr = testArr;

testArr = nil;
NSLog(@"print weakStr is %@", weakStrArr);

// 打印结果
2021-05-30 15:39:38.772768+0800 Strong&Weak[3579:203646] print weakStr is (null)
小结>

小结 #

对比以上结果,可以看出不使用__strong修饰和使用__strong结果一样,说明oc默认情况下声明变量都是__strong,因为weak修饰引用计数器不会+1,所修饰的对象可能随时被释放。

weak是弱引用,不会持有对象,引用计数器不会+1>

weak是弱引用,不会持有对象,引用计数器不会+1 #

常用于修饰UI控件、delegate

声明为weak的指针,weak指针指向的对象一旦被释放,weak的指针都将被赋值为nil,防止野指针。

copy分为浅拷贝、深拷贝>

copy分为浅拷贝、深拷贝 #

修饰NSString、block

stackblock如果不copy的话,stackblock是存放在栈里面的,他的生命周期会随着函数的结束而出栈的,copy之后会转变为mallocblock放在堆里面。

assign简单赋值,不改变引用计数。>

assign简单赋值,不改变引用计数。 #

  • 基础数据类型(NSInteger、CGFloat)
  • C数据类型(int、float、double、char等)
  • 枚举、结构体等非OC对象


Objc - 系列文章之一
Part 1: 当前阅读