iOS底层学习-day-26
前言-OC-内存管理篇
我是一名iOS开发者, iOS底层 菜鸟的进阶之路30天。
UITextField中的placeholder都是不可变的
@property(nullable, nonatomic,copy) NSString *placeholder;
//都是分可变和不可变的
NSArray, NSMutableArray;
NSDictionary, NSMutableDictionary;
NSString, NSMutableString;
NSData, NSMutableData;
NSSet, NSMutableSet;
类进行copy
- MJPerson.h
#import <Foundation/Foundation.h>
@interface MJPerson : NSObject <NSCopying>
@property (assign, nonatomic) int age;
@property (assign, nonatomic) double weight;
@end
- MJPerson.m
#import "MJPerson.h"
@implementation MJPerson
- (id)copyWithZone:(NSZone *)zone {
MJPerson *person = [[MJPerson allocWithZone:zone] init];
person.age = self.age;
person.weight = self.weight;
return person;
}
- (NSString *)description {
return [NSString stringWithFormat:@"age = %d, weight = %f", self.age, self.weight];
}
@end
- 使用
MJPerson *p1 = [[MJPerson alloc] init];
p1.age = 20;
p1.weight = 50;
MJPerson *p2 = [p1 copy];
p2.age = 30;
NSLog(@"%@", p1);
NSLog(@"%@", p2);
ARC
// ARC是LLVM编译器和Runtime系统相互协作的一个结果
__strong MJPerson *person1;
__weak MJPerson *person2;//指向的值会自动清空
__unsafe_unretained MJPerson *person3;//指向的值不会自动清空
NSLog(@"111");
{
MJPerson *person = [[MJPerson alloc] init];
person3 = person;
}
NSLog(@"222 - %@", person3);
autorelease
- oc 的 autorelease 在c++中的结果
struct __AtAutoreleasePool {
__AtAutoreleasePool() { // 构造函数,在创建结构体的时候调用
atautoreleasepoolobj = objc_autoreleasePoolPush();
}
~__AtAutoreleasePool() { // 析构函数,在结构体销毁的时候调用
objc_autoreleasePoolPop(atautoreleasepoolobj);
}
void * atautoreleasepoolobj;
};
{
__AtAutoreleasePool __autoreleasepool;
MJPerson *person = ((MJPerson *(*)(id, SEL))(void *)objc_msgSend)((id)((MJPerson *(*)(id, SEL))(void *)objc_msgSend)((id)((MJPerson *(*)(id, SEL))(void *)objc_msgSend)((id)objc_getClass("MJPerson"), sel_registerName("alloc")), sel_registerName("init")), sel_registerName("autorelease"));
}
atautoreleasepoolobj = objc_autoreleasePoolPush();
MJPerson *person = [[[MJPerson alloc] init] autorelease];
objc_autoreleasePoolPop(atautoreleasepoolobj);