iOS开发 - 开发中容易遇到的问题
▶ 循环引用问题
循环引用的本质问题就是双方都强引用了彼此,下面以 MRC模式 为例
// - main.m
#import <Foundation/Foundation.h> #import "Person.h" #import "Animal.h" int main(int argc, const char * argv[]) { //------------ 循环引用:双方都 retain 了彼此 ---------- // Animal *a = [[Animal alloc] init];// 1 // Person *p = [[Person alloc] init];// 1 // a.per = p;// +1 // p.cat = a;// +1 // NSLog(@"%ld",a.retainCount);// 2 // NSLog(@"%ld",p.retainCount);// 2 // [a release];// 1 // [p release];// 1 // NSLog(@"%ld",a.retainCount);// 1 // NSLog(@"%ld",p.retainCount);// 1 // // 造成的问题就是 谁也释放不掉谁 // ------------ 打破循环引用:在任一方,把 retain 改成 assign 即可 ------------ Animal *a1 = [[Animal alloc] init];// 1 Person *p1 = [[Person alloc] init];// 1 a1.per = p1;// p1+1 p1.cat = a1;// a1+0 NSLog(@"%ld",a1.retainCount);// 1 NSLog(@"%ld",p1.retainCount);// 2 // 验证一 // [p1 release];// 两者的 dealloc 均不会触发 // [a1 release];// Animal 触发 dealloc!其中 self.per = nil 执行后,Person 触发 dealloc // 验证二 [a1 release];// Animal 触发 dealloc! 其中 self.per = nil 执行后,p1 的引用计数 -1 [p1 release];// Person 触发 dealloc return 0; }
// - Animal.h
@class Person; #import <Foundation/Foundation.h> @interface Animal : NSObject @property(nonatomic,retain)Person *per; @end
// - Animal.m
#import "Animal.h" @implementation Animal -(void)dealloc{ NSLog(@"Animal 触发"); self.per = nil; [super dealloc]; } @end
// - Person.h
@class Animal; #import <Foundation/Foundation.h> @interface Person : NSObject // 循环引用 //@property(nonatomic,retain)Animal *cat; // 打破循环引用:ARC模式 下使用 weak @property(nonatomic,assign)Animal *cat; @end
// - People.m
#import "Person.h" @implementation Person -(void)dealloc{ NSLog(@"Person 触发"); self.cat = nil; [super dealloc]; } @end
▶ iOS 中结构体作为对象的属性时,其成员不允许被单独修改
DemoA:以 frame 为例
UIView *demoV = [[UIView alloc] initWithFrame:CGRectMake(80, 200, 200, 60)]; demoV.backgroundColor = [UIColor redColor]; [self.view addSubview:demoV]; demoV.frame.size = CGSizeMake(60.4, 60.4); // 编译不通过 demoV.frame.origin = CGPointMake(20.0, 20.0); // 编译不通过
// 如何解决:指针重指向 CGRect frame = demoV.frame; frame.size.height = 300; frame.size.width = 300; demoV.frame = frame;
分类:
iOS章节
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律