iphone sdk5.0关于内存管理及ARC

RAG系统优化:分层索引与混合计算架构实践 检索增强生成(RAG)技术通过结合向量检索与大型语言模型(LLM),有效解决了传统NLP模型的知识时效性问题。其核心原理是利用向量相似性搜索从外部知识库动态获取信息,再通过LLM生成高质量回答。在工程实践中,CPU-GPU异构计算架构成为主流方案,但面临维度灾难、资源争用和长尾效应等挑战。针对这些痛点,分层索引设计和混合精度计算等优化技术应运而生,特别适用于实时问答、智能客服等需要低延迟高并发的场景。实验数据显示,采用热冷数据分离策略的VectorLiteRAG方案,能在GPU内存占用减少75%的情况下,将 阅读详情

转载自  http://www.devdiv.com/home.php?mod=space&uid=121351&do=blog&id=6234


最近比较忙,新的文档下载了一直没时间读,偶尔看见csdn的一篇关于xcode4.2sdk5.0的文章,翻译的不错,拿过来分享一下,感谢翻译者。

ARC(Automatic Reference Counting )技术概述

Automatic Reference Counting (ARC) 是一个编译期的技术,利用此技术可以简化Objective-C编程在内存管理方面的工作量。

这里我把此技术翻译为自动内存计数器管理技术,下图是使用和不使用此技术的Objective-C代码的区别。


ARC技术是随着XCode4.2一起发布的,在缺省工程模板中,你可以指定你的工程是否支持ARC技术,如果你不指定工程支持ARC技术,在代码中你必须使用管理内存的代码来管理内存。

概述

自动计数(ARC)是一个编译期间工作的能够帮你管理内存的技术,通过它,程序人员可以不需要在内存的retain,释放等方面花费精力。

ARC在编译期间为每个Objective-C指针变量添加合适的retain, release, autorelease等函数,保存每个变量的生存周期控制在合理的范围内,以期实现代码上的自动内存管理。

In order for the compiler to generate correct code, ARC imposes some restrictions on the methods you can use, and on how you use toll-free bridging (see “Toll-Free Bridged Types”); ARC also introduces new lifetime qualifiers for object references and declared properties.

你可以使用编译标记-fobjc-arc来让你的工程支持ARC。ARC在Xcode4.2中引入,在Mac OS X v10.6,v10.7 (64位应用),iOS 4,iOS 5中支持,Xcode4.1中不支持这个技术.

如果你现在的工程不支持ARC技术,你可以通过一个自动转换工具来转换你的工程(工具在Edit->Convert menu),这个工具会自动所有工程中手动管理内存的点转换成合适自动方式的(比如移除retain, release等)。这个工具会转换工程中所有的文件。当然你可以转换单个文件。

ARC提供自动内存管理的功能

ARC使得你不需要再思考何时使用retain,release,autorelease这样的函数来管理内存,它提供了自动评估内存生存期的功能,并且 在编译期间自动加入合适的管理内存的方法。编译器也会自动生成dealloc函数。一般情况下,通过ARC技术,你可以不顾传统方式的内存管理方式,但是 深入了解传统的内存管理是十分有必要的。

下面是一个person类的一个声明和实现,它使用了ARC技术。

@interface Person : NSObject
@property (nonatomic, strong) NSString *firstName;
@property (nonatomic, strong) NSString *lastName;
@property (nonatomic, strong) NSNumber *yearOfBirth;
@property (nonatomic, strong) Person *spouse;
@end
 
@implementation Person
@synthesize firstName, lastName, yearOfBirth, spouse;
@end

(有关strong的帮助,请参考 “ARC Introduces New Lifetime Qualifiers.”)

使用ARC,你可以象下面的方式实现contrived函数:

- (void)contrived {
    Person *aPerson = [[Person alloc] init];
    [aPerson setFirstName:@"William"];
    [aPerson setLastName:@"Dudney"];
    [aPerson:setYearOfBirth:[[NSNumber alloc] initWithInteger:2011]];
    NSLog(@"aPerson: %@", aPerson);
}

ARC管理内存,所以这里你不用担心aPerson和NSNumber的临时变量会造成内存泄漏。

你还可以象下面的方式来实现Person类中的takeLastNameFrom:方法,

- (void)takeLastNameFrom:(Person *)person {
    NSString *oldLastname = [self lastName];
    [self setLastName:[person lastName]];
    NSLog(@"Lastname changed from %@ to %@", oldLastname, [self lastName]);
}

ARC可以保证在NSLog调用的时候,oldLastname还存在于内存中。

ARC中的新规则

为了ARC能顺利工作,特增加如下规则,这些规则可能是为了更健壮的内存管理,也有可能为了更好的使用体验,也有可能是简化代码的编写,不论如何,请不要违反下面的规则,如果违反,将会得到一个编译期错误。

  • 下面的这些函数:dealloc,retain, release, retainCount, autorelease。禁止任何形式调用和实现(dealloc可能会被实现),包括使用@selector(retain), @selector(release)等的隐含调用。

    你可能会实现一个和内存管理没有关系的dealloc,譬如只是为了调用[systemClassInstance setDelegate:nil] ,但是请不要调用[super dealloc] ,因为编译器会自动处理这些事情。

  • 你不可以使用NSAllocateObject或者NSDeallocateObject.

    使用alloc申请一块内存后,其他的都可以交给运行期的自动管理了。

  • 不能在C语言中的结构中使用Objective-c中的类的指针。

    请使用类类管理数据。

  • 不能使用NSAutoreleasePool.

    作为替代,@autoreleasepool被引入,你可以使用这个效率更高的关键词。

  • 不能使用memory zones.

    NSZone不再需要—本来这个类已经被现代Objective-c废弃。

ARC在函数和便利变量命名上也有一些新的规定

  • 禁止以new开头的属性变量命名。

ARC Introduces New Lifetime Qualifiers

ARC introduces several new lifetime qualifiers for objects, and zeroing weak references. A weak reference does not extend the lifetime of the object it points to. A zeroing weak reference automatically becomes nil if the object it points to is deallocated.

You should take advantage of these qualifiers to manage the object graphs in your program. In particular, ARC does not guard against strong reference cycles (previously known as retain cycles—see “Practical Memory Management”). Judicious use of weak relationships will help to ensure you don’t create cycles.

属性变量修饰符

weak和strong两个修饰符是新引进的,使用例子如下:

// 下面的作用和: @property(retain) MyClass *myObject;相同
@property(strong) MyClass *myObject;
 
// 下面的作用和"@property(assign) MyClass *myObject;"相识
// 不同的地方在于,如果MyClass的实例析构后,这个属性变量的值变成nil,而不是一个野指针,
 
@property(weak) MyClass *myObject;
Variable Qualifiers

You use the following lifetime qualifiers for variables just like you would, say, const.

__strong
__weak
__unsafe_unretained
__autoreleasing

__strong is the default. __weak specifies a zeroing weak reference to an object. __unsafe_unretained specifies weak reference to an object that is not zeroing—if the object it references is deallocated, the pointer is left dangling. You use__autoreleasing to denote arguments that are passed by reference (id *) and are autoreleased on return.

Take care when using __weak variables on the stack. Consider the following example:

NSString __weak *string = [[NSString alloc] initWithFormat:@"First Name: %@", [self firstName]];
NSLog(@"string: %@", string);

Although string is used after the initial assignment, there is no other strong reference to the string object at the time of assignment; it is therefore immediately deallocated. The log statement shows that string has a null value.

You also need to take care with objects passed by reference. The following code will work:

NSError *error = nil;
BOOL OK = [myObject performOperationWithError:&error];
if (!OK) {
    // Report the error.
    // ...

However, the error declaration is implicitly:

NSError * __strong e = nil;

and the method declaration would typically be:

-(BOOL)performOperationWithError:(NSError * __autoreleasing *)error;

The compiler therefore rewrites the code:

NSError __strong *error = nil;
NSError __autoreleasing *tmp = error;
BOOL OK = [myObject performOperationWithError:&tmp];
error = tmp;
if (!OK) {
    // Report the error.
    // ...

The mismatch between the local variable declaration (__strong) and the parameter (__autoreleasing) causes the compiler to create the temporary variable. You can get the original pointer by declaring the parameter id __strong * when you take the address of a __strong variable. Alternatively you can declare the variable as __autoreleasing.

Use Lifetime Qualifiers to Avoid Strong Reference Cycles

You can use lifetime qualifiers to avoid strong reference cycles. For example, typically if you have a graph of objects arranged in a parent-child hierarchy and parents need to refer to their children and vice versa, then you make the parent-to-child relationship strong and the child-to-parent relationship weak. Other situations may be more subtle, particularly when they involve block objects.

In manual reference counting mode, __block id x; has the effect of not retaining x. In ARC mode, __block id x; defaults to retaining x (just like all other values). To get the manual reference counting mode behavior under ARC, you could use__unsafe_unretained __block id x;. As the name __unsafe_unretained implies, however, having a non-retained variable is dangerous (because it can dangle) and is therefore discouraged. Two better options are to either use __weak (if you don’t need to support iOS 4 or OS X v10.6), or set the __block value to nil to break the retain cycle.

The following code fragment illustrates this issue using a pattern that is sometimes used in manual reference counting.

MyViewController *myController = [[MyViewController alloc] init…];
// ...
myController.completionHandler =  ^(NSInteger result) {
   [myController dismissViewControllerAnimated:YES completion:nil];
};
[self presentViewController:myController animated:YES completion:^{
   [myController release];
}];

As described, instead, you can use a __block qualifier and set the myController variable to nil in the completion handler:

__block MyViewController *myController = [[MyViewController alloc] init…];
// ...
myController.completionHandler =  ^(NSInteger result) {
    [myController dismissViewControllerAnimated:YES completion:nil];
    myController = nil;
};

Alternatively, you can use a temporary __weak variable. The following example illustrates a simple implementation:

MyViewController *myController = [[MyViewController alloc] init…];
// ...
__weak MyViewController *weakMyViewController = myController;
myController.completionHandler =  ^(NSInteger result) {
    [weakMyViewController dismissViewControllerAnimated:YES completion:nil];
};

For non-trivial cycles, however, you should use:

MyViewController *myController = [[MyViewController alloc] init…];
// ...
__weak MyViewController *weakMyController = myController;
myController.completionHandler =  ^(NSInteger result) {
    MyViewController *strongMyController = weakMyController;
    if (strongMyController) {
        // ...
        [strongMyController dismissViewControllerAnimated:YES completion:nil];
        // ...
    }
    else {
        // Probably nothing...
    }
};

In some cases you can use __unsafe_unretained if the class isn’t __weak compatible. This can, however, become impractical for nontrivial cycles because it can be hard or impossible to validate that the __unsafe_unretained pointer is still valid and still points to the same object in question.

自动释放池

使用ARC,你不能使用NSAutoReleasePool类来管理自动释放池了,作为替代,ARC使用一个新的语法结构:

@autoreleasepool {
     // Code, such as a loop that creates a large number of temporary objects.
}

编译器根据工程是否使用ARC,来决定这个语法结构最终呈现方式,这个语法结构使用了一种比NSAutoReleasePool更高效的方式。

Outlets

The patterns for declaring outlets in iOS and OS X change with ARC and become consistent across both platforms. The pattern you should typically adopt is: outlets should be weak, except for those from File’s Owner to top-level objects in a nib file (or a storyboard scene) which should be strong.

Outlets that you create should will therefore generally be weak by default:

  • Outlets that you create to, for example, subviews of a view controller’s view or a window controller’s window, are arbitrary references between objects that do not imply ownership.

  • The strong outlets are frequently specified by framework classes (for example, UIViewController’s view outlet, or NSWindowController’s window outlet).

For example:

@interface MyFilesOwnerClass : SuperClass
 
@property (weak) IBOutlet MyView *viewContainerSubview;
@property (strong) IBOutlet MyOtherClass *topLevelObject;
@end

In cases where you cannot create a weak reference to an instance of a particular class (such as NSTextView), you should use assign rather than weak:

@property (assign) IBOutlet NSTextView *textView;

This pattern extends to references from a container view to its subviews where you have to consider the internal consistency of your object graph. For example, in the case of a table view cell, outlets to specific subviews should again typically beweak. If a table view contains an image view and a text view, then these remain valid so long as they are subviews of the table view cell itself.

Outlets should be changed to strong when the outlet should be considered to own the referenced object:

  • As indicated previously, this often the case with File’s Owner: top level objects in a nib file are frequently considered to be owned by the File’s Owner.

  • You may in some situations need an object from a nib file to exist outside of its original container. For example, you might have an outlet for a view that can be temporarily removed from its initial view hierarchy and must therefore be maintained independently.

其他的新功能

使用ARC技术,可以使得在栈上分配的指针隐式的初始化为nil,比如

- (void)myMethod {
    NSString *name;
    NSLog(@"name: %@", name);
}

上面的代码会Log出来一个null,不会象不使用ARC技术的时候使得程序崩溃。


Xcode 15.4 与 16.2 版本对比:Swift 5.10 到 6.0 的3大兼容性变化 当Xcode从15.4版本演进到16.2时,Swift语言也完成了从5.10到6.0的关键跨越。这两个版本的差异不仅体现在开发工具的功能增强上,更在语言层面带来了范式转变。在实际项目中,我们发现逐步迁移比全量切换更稳妥。一个典型的成功案例是先将非关键模块迁移到Swift 6,观察两周稳定性后再处理核心模块。在底层架构上,Xcode 16.2引入了全新的Swift 6语言模式,这是自Swift 4以来最重要的ABI稳定化升级。Swift 6最显著的变革是引入了严格的并发安全模型。 阅读详情

相关推荐

重读2007年Objective-C前言:iOS开发的底层契约与精神源流

Objective-C是苹果早期iOS生态的基石语言,其核心在于C语言的底层控制力与Smalltalk面向对象思想的融合。它通过Runtime动态消息机制、toll-free bridging跨框架互通、协议(Protocol)驱动的鸭子类型等设计,构建了高度灵活又强约束的开发范式。这种‘契约优先’的思想深刻影响了后续Swift的内存所有权模型、Delegate向AsyncSequence的演进,以及UIKit到SwiftUI的架构迁移。理解Objective-C并非怀旧,而是掌握iOS平台级开发的本质逻辑

chuji3953的博客 425

object c_ARC机制

ARC是iOS 5推出的新功能,全称叫 ARC(Automatic Reference Counting)。简单地说,就是代码中自动加入了retain/release,原先需要手动添加的用来处理内存管理的引用计数的代码可以自动地由编译器完成了。该机制在 iOS 5/ Mac OS X 10.7 开始导入,利用 Xcode4.2 可以使用该机制。简单地理解ARC,就是通过指定的语法,让编译器(LLV

Dream_We的专栏 773

1、 入门iOS开发:从零开始构建你的第一个iPhone应用

本文带你进入iOS开发的世界,从零开始学习如何使用XCode和iOS SDK构建第一个iPhone应用。内容涵盖项目创建、用户界面设计、调试技巧以及编码规范等基础知识,并通过实战演练巩固所学技能。适合初学者入门iOS开发。

weixin_42452483的博客 366

IOS 5编程 内存管理 ARC技术概述

ARC(Automatic Reference Counting)技术概述 此文章由Tom翻译,首发于csdn的blog,任何人都可以转发,但是请保留原始链接和翻译者得名字。多谢! Automatic Reference Counting (ARC) 是一个编译期的技术,利用此技术可以简化Objective-C编程在内存管理方面的工作量。 这里我把此技术翻译为自动内存...

sogotobj 224

告别Sourceforge安装器!手把手教你下载MinGW-w64离线包并配置环境变量(Windows 10/11)

本文详细介绍了如何在Windows 10/11系统上通过下载MinGW-w64离线包并配置环境变量,完全绕过Sourceforge安装器的问题。从选择正确的版本、解压到本地目录,到设置系统环境变量和验证编译环境,手把手指导开发者快速搭建稳定的GCC编译环境,解决常见的安装困扰。

weixin_30896825的博客 345

Quartz定时任务调度框架中的Misfire策略实战解析

本文深入解析了Quartz定时任务调度框架中的Misfire(失火)处理策略。针对SimpleTrigger和CronTrigger两种常用触发器,详细对比了其各自的Misfire指令(如NowWithExistingCount、FireAndProceed等)的核心行为与适用场景,并提供了基于不同业务需求(如数据补跑、时间点敏感度)的实战选型指南,帮助开发者构建更健壮可靠的任务调度系统。

weixin_29250573的博客 95

1.ARC

1.简介 该部分笔记总结自《Object-C高级编程》和《疯狂iOS讲义》2.ARC是通过引用计数来实现一种引用计数的方式。 将对象分成4个状态,生成,持有,释放,废弃。方式如下: 生成并持有对象 alloc/new/copy/mutableCopy等方法 持有对象 retain 释放对象 release

zhang_int_int的专栏 462

SX1281IMLTRT---LoRa超高性能应用且最优性价比的2.4GHz解决方案

SX1281IMLTRT是Semtech推出的高性能2.4GHz射频收发器,专为高速数据传输和精准测距优化。支持FSK/BLE5.0调制,传输速率达2Mbps,集成TW-ToF硬件测距引擎,精度达亚米级。适用于工业4.0、无人机、RTLS等场景,兼具全球通用频段和低功耗优势,提供高性价比解决方案。

DN13826545134的博客 739

objective-c中ARC机制

一、ARC介绍 Apple的文档里是这么定义ARC的: “自动引用计数(ARC)是一个编译器级的功能,它能简化Cocoa应用中对象生命周期管理(内存管理)的流程。” ARC并不是垃圾收集,而且,引用计数也没有消失,只是变成自动而已。 二、ARC使用原理 当采用ARC后,代码只要这样写: NSObject *obj = [[NSObject alloc] init]; /

aa641462576的专栏 471

C#+Winform+OpenCvSharp实战:5步搞定工业视觉检测框架(附源码下载)

本文详细介绍了如何使用C#、Winform和OpenCvSharp构建工业视觉检测框架,通过5个关键步骤实现高效、稳定的视觉检测系统。内容涵盖环境配置、相机集成、核心算法实现、系统集成与通信,以及部署优化,帮助开发者快速掌握工业视觉检测技术,提升检测精度和效率。附完整源码下载,助力工业数字化转型。

pz89012345的博客 553

三菱PLC通信库大比拼:手把手教你用C#实现最高效的McProtocol数据读写

本文深入比较了三菱PLC通信库的性能,重点介绍了如何使用C#高效实现McProtocol数据读写。通过实测数据对比HslCommunication、McProtocol-next和自定义方案的优劣,提供优化技巧和代码示例,帮助开发者在工业自动化场景中提升通信效率。

m0n1o2p的博客 269

iPhone开发 在xcode4.2中sdk5.0 arc部分不开启

一般都是开启arc功能,毕竟不需要自己手动去释放,是一件比较轻松的事情。 但是我们在引用第三方的时候,基本上都是带release与retain的方法,这个时候代码编译就通不过 我们可以设置部分文件不使用arc,这样就可以兼容了。 步骤: 1.在builde phases 中,compile sources   2.选中文件,双击文件,在弹出框中输入-fno-objc-

Linlei的专栏 656

LangGraph实战训练营-从零构建AI驱动的wiki知识库

本文深入解析 LangChain 团队开源的 Deep Agents 框架核心示例——LLM Wiki,一个基于大语言模型自动构建和维护持久化知识库的生产级 AI Agent 系统。文章从项目架构、环境搭建、核心原理到实战操作全面展开:详解 CompositeBackend 组合后端与细粒度权限控制的安全设计、四种工作模式(初始化/摄取/查询/质量检查)的完整流程、LangSmith 远程沙箱的隔离执行机制,以及人机协同审核(HITL)的实践应用。

program哲学 220

iphone中xcode4.2中取消arc

    sdk5的xcode自带了arc,虽然arc是比gc强大很多,但由于开发的习惯性,还有框架不适应,在arc还没足够稳定和安全以前,暂时还是使用手动alloc和release等。   至于如果取消arc,分3步:   1、project -> Build settings -> Apple LLVM complier 3.0 - Language -> obje...

wsq198760的专栏 97

基于卷积神经网络的试卷手写分数自动识别系统

本文提出了一种基于卷积神经网络(CNN)的试卷手写分数自动识别系统,旨在解决传统人工录入方式效率低、易出错的问题。系统通过图像预处理、分数区域定位、CNN识别和后处理等模块,实现了对手写数字分数的端到端自动识别。针对试卷复杂背景、书写风格多样等技术挑战,系统采用中等深度的CNN架构,在构建的数据集上取得了99.5%以上的识别准确率。该系统可显著提升教育评估工作的效率和准确性,具有重要的实用价值。

huanghm88的专栏 230

Openclaw错误排查及解决方案之:Something went wrong while processing your request. Please try again.

Openclaw错误排查及解决方案之:Something went wrong while processing your request. Please try again.

多媒体编程、网络编程、系统编程、网络安全编程、驱动编程 3813

如何学好iphone游戏开发

如何学好iphone游戏开发     自从发布《如何学习iphone游戏开发》到现在,大概有半年时间了。其实在写《如何学习iphone游戏开发》的时候,我就写下豪言,说哪天学好了,再来写一篇《如何学好iphone游戏开发》。但是现在,当我坐下来写这篇文章的时候,心里还是有点忐忑不安的,怕写不好,或者水平不够,写出来的东西达不到预期的效果。但是,管他呢,我手写我口,我把自己这半年来的学习经历和

zplove003的专栏 896

霍尼韦尔SoftMaster使用说明

霍尼韦尔SoftMaster使用说明

如何学习iphone游戏开发

子龙山人 Learning,Sharing,Improving! 如何学好iphone游戏开发     自从发布《如何学习iphone游戏开发》到现在,大概有半年时间了。其实在写《如何学习iphone游戏开发》的时候,我就写下豪言,说哪天学好了,再来写一篇《如何学好iphone游戏开发》。但是现在,当我坐下来写这篇文章的时候,心里还是有点忐忑不安的,怕写不好,或者水平不够

822

廖雪峰Python教程[完整版]

廖雪峰的python教程整理的,已经排好版了,而且还是完整的,适合小白

vb 6.0并口开发操作实例

vb6并口开发,简体中文,试例内有inpout32.dll动态链接库

iOS 开发百问(7)

71、如何让UIWebView的大小符合HTML的内容?在 iOS 5中,这很简单,设置 webview 的委托,然后在委托中实现didFinishLoad:方法:- (void)webViewDidFinishLoad:(UIWebView *)webView{    CGSize size=webView.scrollView.contentSize;//iOS 5+    webView.b

kmyhy的专栏 1万+

老版QQ原生表情gif动态

这是老版的QQ表情,不过全是动态的的,Windows照片查看器是不会动的,可以右击用浏览器打开查看,再说一遍是老版的,只是分享给宁愿用老版也要动态的人。

(转载)如何学好iphone游戏开发

  转自:http://www.cnblogs.com/zilongshanren/archive/2011/09/19/2181558.html   自从发布《如何学习iphone游戏开发》到 现在,大概有半年时间了。其实在写《如何学习iphone游戏开发》的时候,我就写下豪言,说哪天学好了,再来写一篇《如何学好iphone游戏开发》。 但是现在,当我坐下来写这篇文章的时候,心里还是有点忐...

weixin_34146410的博客 280
上一篇: iPhone Mac 通讯
下一篇: xlsx数据导入到Sqlite数据库
getengwork
博客等级 码龄15年 0粉丝 0原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值
⌂ 换网址