Automatic Reference Counting (ARC) makes memory management the job of the compiler by inserting retain and release calls. ARC consists of a frontend compiler that inserts the appropriate memory management calls and an optimizer that removes unnecessary calls. ARC supports iOS 5+ and OS X 10.7+ and allows using variable ownership qualifiers like __strong (default), __weak, __unsafe_unretained, and __autoreleasing to avoid retain cycles.
JavaScript - An Introduction is a beginner's guide to JavaScript. It starts with very basic level and goes to intermediate level. You'll be introduced with every language constructs, Event handling, Form handling and AJAX which is supported by JavaScript with XMLHttpRequest object. This XHR object is discussed in enough detail so that you can understand how the underlying AJAX functionality works in jQuery. At the end it discusses advance concepts and library build on/around JavaScript.
Le slide deck de l'Université que nous avons donnée avec Rémi Forax à Devoxx France 2019.
Comme promis, Java sort sa version majeure tous les 6 mois. Le train passe et amène son lot de nouveautés. Parmi elles, certaines sont sorties : une nouvelle syntaxe pour les clauses switch et l'instruction de byte code CONSTANT_DYNAMIC. D'autres sont en chantier, plus ou moins avancé : une nouvelle façon d'écrire des méthodes de façon condensée, un instanceof 'intelligent', des constantes évaluées au moment où elles sont utilisées. Les projets progressent. Loom, et son nouveau modèle de programmation concurrente que l'ont peut tester avec Jetty. Amber, qui introduit les data types et des nouvelles syntaxes. Valhalla, dont les value types donnent leurs premiers résultats. S'il est difficile de prévoir une date de sortie pour ces nouveautés, on sait en revanche qu'une fois prêtes elles sortiront en moins de 6 mois. De tout ceci nous parlerons donc au futur et en public, avec des démonstrations de code, des slides, du code, de la joie et de la bonne humeur !
JRuby 9000 introduced a new intermediate representation that allows us to use classic compiler strategies to optimize Ruby. This talk describes what we're doing with this new IR and why current JVM capabilities are not sufficient.
Inside the JVM - Follow the white rabbit! / Breizh JUGSylvain Wallez
Presentation given at the Rennes (FR) Java User Group in Feb 2019.
How do we go from your Java code to the CPU assembly that actually runs it? Using high level constructs has made us forget what happens behind the scenes, which is however key to write efficient code.
Starting from a few lines of Java, we explore the different layers that constribute to running your code: JRE, byte code, structure of the OpenJDK virtual machine, HotSpot, intrinsic methds, benchmarking.
An introductory presentation to these low-level concerns, based on the practical use case of optimizing 6 lines of code, so that hopefully you to want to explore further!
Feihong talks about PEP 3156 and basic usage of Tulip, the reference implementation.
Video: http://pyvideo.org/video/2194/asynchronous-io-in-python-3
Source code: https://github.com/feihong/tulip-talk/
JavaScript - An Introduction is a beginner's guide to JavaScript. It starts with very basic level and goes to intermediate level. You'll be introduced with every language constructs, Event handling, Form handling and AJAX which is supported by JavaScript with XMLHttpRequest object. This XHR object is discussed in enough detail so that you can understand how the underlying AJAX functionality works in jQuery. At the end it discusses advance concepts and library build on/around JavaScript.
Le slide deck de l'Université que nous avons donnée avec Rémi Forax à Devoxx France 2019.
Comme promis, Java sort sa version majeure tous les 6 mois. Le train passe et amène son lot de nouveautés. Parmi elles, certaines sont sorties : une nouvelle syntaxe pour les clauses switch et l'instruction de byte code CONSTANT_DYNAMIC. D'autres sont en chantier, plus ou moins avancé : une nouvelle façon d'écrire des méthodes de façon condensée, un instanceof 'intelligent', des constantes évaluées au moment où elles sont utilisées. Les projets progressent. Loom, et son nouveau modèle de programmation concurrente que l'ont peut tester avec Jetty. Amber, qui introduit les data types et des nouvelles syntaxes. Valhalla, dont les value types donnent leurs premiers résultats. S'il est difficile de prévoir une date de sortie pour ces nouveautés, on sait en revanche qu'une fois prêtes elles sortiront en moins de 6 mois. De tout ceci nous parlerons donc au futur et en public, avec des démonstrations de code, des slides, du code, de la joie et de la bonne humeur !
JRuby 9000 introduced a new intermediate representation that allows us to use classic compiler strategies to optimize Ruby. This talk describes what we're doing with this new IR and why current JVM capabilities are not sufficient.
Inside the JVM - Follow the white rabbit! / Breizh JUGSylvain Wallez
Presentation given at the Rennes (FR) Java User Group in Feb 2019.
How do we go from your Java code to the CPU assembly that actually runs it? Using high level constructs has made us forget what happens behind the scenes, which is however key to write efficient code.
Starting from a few lines of Java, we explore the different layers that constribute to running your code: JRE, byte code, structure of the OpenJDK virtual machine, HotSpot, intrinsic methds, benchmarking.
An introductory presentation to these low-level concerns, based on the practical use case of optimizing 6 lines of code, so that hopefully you to want to explore further!
Feihong talks about PEP 3156 and basic usage of Tulip, the reference implementation.
Video: http://pyvideo.org/video/2194/asynchronous-io-in-python-3
Source code: https://github.com/feihong/tulip-talk/
Slides della sessione su Automatic Reference Counting, tenuta da Giuseppe Arici alla WhyMCA 2012.
http://www.whymca.org/intervento/automatic-reference-counting
Contents :
Language Concepts
How Objective C works- Basics
Data Types
NSInteger
NSNumber
Operators
Loop
Inheritance
Method Overloading
Mutable and Immutable Strings
Mutable and Immutable Arrays
File Management
Presentation to the MIT IAP HTML5 Game Development Class on Debugging and Optimizing Javascript, Local storage, Offline Storage and Server side Javascript with Node.js
The slides explain Memory management in objective C with reference to Cocoa and IOS. Difference between ARC and manual memory management is explained. Go through the presentation to understand how memory management is done in objective C.
Slides della sessione su Automatic Reference Counting, tenuta da Giuseppe Arici alla WhyMCA 2012.
http://www.whymca.org/intervento/automatic-reference-counting
-----
Presentata da Apple nel corso dell'ultima WWDC, l'Automatic Reference Counting, secondo gli ingegneri di Cupertino, è la soluzione definitiva all'annoso problema della gestione della memoria nello sviluppo di applicazioni Mac e iOS. ARC promette di ridurre notevolmente il carico di lavoro del programmatore, limitando al minimo la possibilità di errore ed assicurando al contempo un aumento significativo delle prestazioni. Nella compilazione di codice Objective-C, con ARC, il programmatore è sollevato dalla responsabilità di applicare in modo meccanico e ripetitivo le regole fondamentali della gestione della memoria. Inoltre ARC si propone di migliorare l'attività di sviluppo, senza per questo gravare sulle prestazioni del sistema, sulla durata della batteria e sulla sicurezza del codice prodotto. In un ambiente nativo con accesso libero ai puntatori, ARC rappresenta il migliore compromesso possibile tra la gestione manuale della memoria e la garbage collection completamente automatica.
In questa sessione si presenteranno le pratiche che permettono di sfruttare al meglio le potenzialità di ARC, si illustreranno le tecniche di migrazione del codice preesistente al nuovo modello di gestione della memoria e si esamineranno i problemi più ricorrenti che si possono incontrare utilizzando ARC in progetti di media complessità.
Slides for the 1st lecture on mobile development (dedicated to iOS) at the Faculty of Mathematics and Physics at the Charles University in Prague.
Course page: http://www.inmite.eu/en/talks/mff-2012
In the past few years, the bar for exploitation was raised highly, and in the current state of software security it is harder and harder to make successful exploitation on newest operating systems.
But as some systems continue to evolve and introduce new mitigations, the others just freeze a few years behind. In our talk we will focus on rooting Android by two racing conditions vulnerabilities. We will show the differences between level of exploitation needed, and how some mobile vendors are killing offered security features.
2018 Jul 25th LINE Developer Meetup #41 in Fukuoka
Session Slide in English / セッションスライドです。
Graal in GraalVM - A New JIT Compiler
オラクル社からGraalVMというものが発表され、話題を呼んでいます。GraalVMはHotSpot VM上に新しいJITコンパイラGraalと言語実装用フレームワーク/ASTインタプリタであるTruffle、さらにネイティブイメージ作成機能とその実行に使われるSubstrateVMを併せ持ったものです。すでにTruffleを使用したJavaScriptやRuby、R、Pythonの実装も提供されており、これらの言語とJavaはコードから相互に呼び出しができます。このセッションではGraalVMを概観したあと、JITコンパイラGraalにとくに注力して解説します。GraalとTruffleはOracle Labsとヨハネス・ケプラー大学で共同研究されており、多くの論文が発表されています。HotSpotのJITコンパイラとパフォーマンスや構造などを比較しつつ、GraalのJITコンパイルのテクニックについてもいくつか触れます。とにかく、私がGraalをとても好きなのです。デモも実施しつつ、Graalのすごさを伝えられればと考えています。
The PPTs from one of the event of iWillStudy.com - a leading start-up in the education space in India. This PPT is being used at an event where they taught iPhone programming and applications development.
Similar to Automatic Reference Counting @ Pragma Night (20)
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...James Anderson
Effective Application Security in Software Delivery lifecycle using Deployment Firewall and DBOM
The modern software delivery process (or the CI/CD process) includes many tools, distributed teams, open-source code, and cloud platforms. Constant focus on speed to release software to market, along with the traditional slow and manual security checks has caused gaps in continuous security as an important piece in the software supply chain. Today organizations feel more susceptible to external and internal cyber threats due to the vast attack surface in their applications supply chain and the lack of end-to-end governance and risk management.
The software team must secure its software delivery process to avoid vulnerability and security breaches. This needs to be achieved with existing tool chains and without extensive rework of the delivery processes. This talk will present strategies and techniques for providing visibility into the true risk of the existing vulnerabilities, preventing the introduction of security issues in the software, resolving vulnerabilities in production environments quickly, and capturing the deployment bill of materials (DBOM).
Speakers:
Bob Boule
Robert Boule is a technology enthusiast with PASSION for technology and making things work along with a knack for helping others understand how things work. He comes with around 20 years of solution engineering experience in application security, software continuous delivery, and SaaS platforms. He is known for his dynamic presentations in CI/CD and application security integrated in software delivery lifecycle.
Gopinath Rebala
Gopinath Rebala is the CTO of OpsMx, where he has overall responsibility for the machine learning and data processing architectures for Secure Software Delivery. Gopi also has a strong connection with our customers, leading design and architecture for strategic implementations. Gopi is a frequent speaker and well-known leader in continuous delivery and integrating security into software delivery.
PHP Frameworks: I want to break free (IPC Berlin 2024)Ralf Eggert
In this presentation, we examine the challenges and limitations of relying too heavily on PHP frameworks in web development. We discuss the history of PHP and its frameworks to understand how this dependence has evolved. The focus will be on providing concrete tips and strategies to reduce reliance on these frameworks, based on real-world examples and practical considerations. The goal is to equip developers with the skills and knowledge to create more flexible and future-proof web applications. We'll explore the importance of maintaining autonomy in a rapidly changing tech landscape and how to make informed decisions in PHP development.
This talk is aimed at encouraging a more independent approach to using PHP frameworks, moving towards a more flexible and future-proof approach to PHP development.
UiPath Test Automation using UiPath Test Suite series, part 4DianaGray10
Welcome to UiPath Test Automation using UiPath Test Suite series part 4. In this session, we will cover Test Manager overview along with SAP heatmap.
The UiPath Test Manager overview with SAP heatmap webinar offers a concise yet comprehensive exploration of the role of a Test Manager within SAP environments, coupled with the utilization of heatmaps for effective testing strategies.
Participants will gain insights into the responsibilities, challenges, and best practices associated with test management in SAP projects. Additionally, the webinar delves into the significance of heatmaps as a visual aid for identifying testing priorities, areas of risk, and resource allocation within SAP landscapes. Through this session, attendees can expect to enhance their understanding of test management principles while learning practical approaches to optimize testing processes in SAP environments using heatmap visualization techniques
What will you get from this session?
1. Insights into SAP testing best practices
2. Heatmap utilization for testing
3. Optimization of testing processes
4. Demo
Topics covered:
Execution from the test manager
Orchestrator execution result
Defect reporting
SAP heatmap example with demo
Speaker:
Deepak Rai, Automation Practice Lead, Boundaryless Group and UiPath MVP
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...Neo4j
Leonard Jayamohan, Partner & Generative AI Lead, Deloitte
This keynote will reveal how Deloitte leverages Neo4j’s graph power for groundbreaking digital twin solutions, achieving a staggering 100x performance boost. Discover the essential role knowledge graphs play in successful generative AI implementations. Plus, get an exclusive look at an innovative Neo4j + Generative AI solution Deloitte is developing in-house.
DevOps and Testing slides at DASA ConnectKari Kakkonen
My and Rik Marselis slides at 30.5.2024 DASA Connect conference. We discuss about what is testing, then what is agile testing and finally what is Testing in DevOps. Finally we had lovely workshop with the participants trying to find out different ways to think about quality and testing in different parts of the DevOps infinity loop.
Epistemic Interaction - tuning interfaces to provide information for AI supportAlan Dix
Paper presented at SYNERGY workshop at AVI 2024, Genoa, Italy. 3rd June 2024
https://alandix.com/academic/papers/synergy2024-epistemic/
As machine learning integrates deeper into human-computer interactions, the concept of epistemic interaction emerges, aiming to refine these interactions to enhance system adaptability. This approach encourages minor, intentional adjustments in user behaviour to enrich the data available for system learning. This paper introduces epistemic interaction within the context of human-system communication, illustrating how deliberate interaction design can improve system understanding and adaptation. Through concrete examples, we demonstrate the potential of epistemic interaction to significantly advance human-computer interaction by leveraging intuitive human communication strategies to inform system design and functionality, offering a novel pathway for enriching user-system engagements.
GridMate - End to end testing is a critical piece to ensure quality and avoid...ThomasParaiso2
End to end testing is a critical piece to ensure quality and avoid regressions. In this session, we share our journey building an E2E testing pipeline for GridMate components (LWC and Aura) using Cypress, JSForce, FakerJS…
GraphRAG is All You need? LLM & Knowledge GraphGuy Korland
Guy Korland, CEO and Co-founder of FalkorDB, will review two articles on the integration of language models with knowledge graphs.
1. Unifying Large Language Models and Knowledge Graphs: A Roadmap.
https://arxiv.org/abs/2306.08302
2. Microsoft Research's GraphRAG paper and a review paper on various uses of knowledge graphs:
https://www.microsoft.com/en-us/research/blog/graphrag-unlocking-llm-discovery-on-narrative-private-data/
Communications Mining Series - Zero to Hero - Session 1DianaGray10
This session provides introduction to UiPath Communication Mining, importance and platform overview. You will acquire a good understand of the phases in Communication Mining as we go over the platform with you. Topics covered:
• Communication Mining Overview
• Why is it important?
• How can it help today’s business and the benefits
• Phases in Communication Mining
• Demo on Platform overview
• Q/A
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdfPaige Cruz
Monitoring and observability aren’t traditionally found in software curriculums and many of us cobble this knowledge together from whatever vendor or ecosystem we were first introduced to and whatever is a part of your current company’s observability stack.
While the dev and ops silo continues to crumble….many organizations still relegate monitoring & observability as the purview of ops, infra and SRE teams. This is a mistake - achieving a highly observable system requires collaboration up and down the stack.
I, a former op, would like to extend an invitation to all application developers to join the observability party will share these foundational concepts to build on:
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Albert Hoitingh
In this session I delve into the encryption technology used in Microsoft 365 and Microsoft Purview. Including the concepts of Customer Key and Double Key Encryption.
Securing your Kubernetes cluster_ a step-by-step guide to success !KatiaHIMEUR1
Today, after several years of existence, an extremely active community and an ultra-dynamic ecosystem, Kubernetes has established itself as the de facto standard in container orchestration. Thanks to a wide range of managed services, it has never been so easy to set up a ready-to-use Kubernetes cluster.
However, this ease of use means that the subject of security in Kubernetes is often left for later, or even neglected. This exposes companies to significant risks.
In this talk, I'll show you step-by-step how to secure your Kubernetes cluster for greater peace of mind and reliability.
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...DanBrown980551
Do you want to learn how to model and simulate an electrical network from scratch in under an hour?
Then welcome to this PowSyBl workshop, hosted by Rte, the French Transmission System Operator (TSO)!
During the webinar, you will discover the PowSyBl ecosystem as well as handle and study an electrical network through an interactive Python notebook.
PowSyBl is an open source project hosted by LF Energy, which offers a comprehensive set of features for electrical grid modelling and simulation. Among other advanced features, PowSyBl provides:
- A fully editable and extendable library for grid component modelling;
- Visualization tools to display your network;
- Grid simulation tools, such as power flows, security analyses (with or without remedial actions) and sensitivity analyses;
The framework is mostly written in Java, with a Python binding so that Python developers can access PowSyBl functionalities as well.
What you will learn during the webinar:
- For beginners: discover PowSyBl's functionalities through a quick general presentation and the notebook, without needing any expert coding skills;
- For advanced developers: master the skills to efficiently apply PowSyBl functionalities to your real-world scenarios.
2. Memory Management
• Manual Reference Counting
• Higher level abstraction than malloc / free
• Straightforward approach, but must adhere to conventions and rules
• Garbage Collection
• Only available for OS X 10.5+, but depracated from 10.8+
• Not available on iOS due to performance concerns
• Automatic Reference Counting (ARC)
• Makes memory management the job of the compiler (and runtime)
• Available for: partially iOS 4+ or OS X 10.6+ / fully iOS 5+ or OS X 10.7+
Pragma Night
4. Manual Reference Counting
(Only) Objective-C objects are reference counted:
• Objects start with retain count of 1 when created
• Increased with retain
• Decreased with release, autorelease
• When count equals 0, runtime invokes dealloc
1 2 1 0
alloc retain release release
dealloc
Pragma Night
5. Objects you create
For objects you create with [[SomeClass alloc] init] or
[myInstance copy] (without autoreleasing):
• Retain should not need to be called
• Release when you are done using it in the {code block}
- (void)someMethod {
NSObject *localObject = [[NSObject alloc] init];
_instanceArray = [[NSArray alloc] initWithObjects:localObject, nil];
[localObject release];
}
- (void)dealloc {
[_instanceVariable release];
[super dealloc];
}
Pragma Night
6. Objects you don’t create
For objects you don’t create (e.g. get from methods):
• Retain only when saving to instance (or static) variable
• Release only if you retained it by saving it (as in above case)
- (void)someMethod {
id localObject = [anArray objectAtIndex:0];
_instanceVariable = [localObject retain];
}
- (void)dealloc {
[_instanceVariable release];
[super dealloc];
}
Pragma Night
7. Autorelease
What if you create an object and you are returning it from a
method, how would you be able to release it?
- (NSArray *)objects {
NSArray *localArray = [[NSArray alloc] init]; ✇
}
return localArray;
Leak !
☠
- (NSArray *)objects {
NSArray *localArray = [[NSArray alloc] init];
return [localArray release];
} Crash !
- (NSArray *)objects {
NSArray *localArray = [[NSArray alloc] init]; ☺
return [localArray autorelease];
} Enjoy !
Pragma Night
8. Autorelease
• Instead of explicitly releasing something, you mark it for a
later release
• An object called autorelease pool manages a set of
objects to release when the pool is released
• Add an object to the release pool by calling autorelease
@autoreleasepool {
// code goes here
}
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
// code goes here
[pool release];
Pragma Night
9. Autorelease
• Autorelease is NOT a Garbage Collector !
It is deterministic ⌚
• Objects returned from methods are understood to be
autoreleased if name is not in implicit retained set
(alloc/new/copy/mutableCopy/init)
• If you spawn your own thread, you’ll have to create your
own NSAutoreleasePool
• Stack based: autorelease pools can be nested
Friday Q&A 2011-09-02: Let's Build NSAutoreleasePool
http://www.mikeash.com/pyblog/friday-qa-2011-09-02-lets-build-nsautoreleasepool.html
Pragma Night
10. The Memory Management Rule
Everything that increases the retain count with
alloc, [mutable]copy[WithZone:], new or retain
is in charge of the corresponding [auto]release.
From C++ to Objective-C
http://pierre.chachatelier.fr/programmation/objective-c.php
Pragma Night
11. Automatic Reference Counting
“Automatic Reference Counting (ARC) in Objective-C
makes memory management the job of the compiler. By
enabling ARC with the new Apple LLVM compiler, you
will never need to type retain or release again,
dramatically simplifying the development process, while
reducing crashes and memory leaks. The compiler has a
complete understanding of your objects, and releases
each object the instant it is no longer used, so apps run
as fast as ever, with predictable, smooth performance.”
(Apple, “iOS 5 for developers” – http://developer.apple.com/technologies/ios5)
Pragma Night
12. Automatic Reference Counting
• The Rule is still valid, but it is managed by the compiler
• No more retain, release, autorelease nor dealloc
• New lifetime qualifiers for objects, which includes zeroing
weak references (only available on iOS 5+ & OS X 10.7+)
• Apple provides a migration tool which is build into Xcode
Pragma Night
14. Requirements
• iOS 5+ & OS X 10.7+ Full Support :)
• iOS 4 & OS X 10.6 (64-bit) No Runtime :(
Pragma Night
15. How it works !?
ARC consists of 2 main components
Frontend Compiler Optimizer
Pragma Night
16. ARC Frontend Compiler
• For every local variable inserts retain and
[auto]release appropriately in the block scope { }
• For every owned instance variable inserts release
appropriately in the dealloc method
• Call the [super dealloc] in dealloc method
• Generates errors when a variable ownership is
not set correctly
Pragma Night
17. Method Family / Ownership
Method Name Family Object Ownership Action
alloc/new/copy/mutableCopy/init Create and have ownership of it
retain Take ownership of it
release Relinquish it
dealloc Dispose of it
Everything Else No ownership !
alloc/new/copy/mutableCopy/init “ The Implicit Retained Set ”
Pragma Night
21. ARC Optimizer
• Optimize the retain and release statements by
removing them if they are inserted multiple times
by the ARC Frontend Compiler
• Ensures that performance is not affected by calling
retain and release multiple times
Pragma Night
25. Variable Ownership Qualifiers
• __strong (default)
• __weak
• __unsafe_unretained
• __autoreleasing
Only For Object Type Variables !
( id | AnyClass : NSObject )
Pragma Night
26. Retain Cycles 1/5
Parent Child
__strong
_view
+1 +1
_delegate
__strong
Controller View
as View Delegate
Pragma Night
27. Retain Cycles 2/5
Parent Child
__strong
_view
= +1
_delegate
__unsafe_unretained
Controller View
as View Delegate
Pragma Night
28. Retain Cycles 3/5
Parent Child
__strong
_view
= +1
_delegate
__weak
Controller View
as View Delegate
Pragma Night
29. Retain Cycles 4/5
dealloc
Parent Child
release
☠
_view
New with ARC in
iOS 5+ & OS X 10.7+
=
_delegate
__weak
Controller View ☺nil
as View Delegate
Pragma Night
31. __strong
/* ARC */
{
id __strong obj1 = [[NSObject alloc] init];
id obj2 = [[NSObject alloc] init];
}
/* not-ARC */
{
id obj1 = [[NSObject alloc] init];
[obj1 release];
}
• Strong reference for the object
• Default for ‘id’ and Object Type Variables !
Pragma Night
32. __weak
/* ARC */
{
id __strong obj1 = [[NSObject alloc] init];
id __weak obj2 = obj1;
}
/* not-ARC */
{
id obj1 = [[NSObject alloc] init];
id obj2 = obj1;
[obj1 release];
}
• No ownership of the object
• When discarded, the variable is assigned to nil
Pragma Night
33. __unsafe_unretained
/* ARC */
{
id __unsafe_unretained obj = [[NSObject alloc] init];
}
Assigning retained object to unsafe_unretained variable; object will be
released after assignment [-Warc-unsafe-retained-assign]
• UNSAFE !
• You must take care of the variables manually
• __weak only for iOS 5+ / OSX 10.7+
Pragma Night
34. __autoreleasing
@autoreleasepool
{
id __strong obj = [NSMutableArray array];
}
- (BOOL) performWithError:(NSError **)error;
- (BOOL) perfomrWithError:(NSError * __autoreleasing *)error;
• Pointer to ‘id’ or to ‘Object Type Variables Pointer’ is
qualified with __autoreleasing as default
Pragma Night
35. Variables Initialization
/* ARC */
id __strong obj1;
id __weak obj2;
id __unsafe_unretained obj3;
id __autoreleasing obj4;
/* not-ARC */
id __strong obj1 = nil;
id
id
__weak obj2 = nil;
__unsafe_unretained obj3;
☠
id __autoreleasing obj4 = nil; Crash !
• Any variables that are qualified with __strong,
__weak and __autoreleasing are initialized with nil
Pragma Night
36. Property
Object Property Modifier Variable Ownership Qualifier
assign __unsafe_unretained
unsafe_unretained __unsafe_unretained
weak __weak
retain __strong
strong __strong
copy __strong *
* Note: new copied object is assigned
Pragma Night
37. Property
• Same ownership rules as instance variables
• Manually declared instance variables has to have
the same ownership qualifier as the property
• Copy: copies the object by using copyWithZone
Pragma Night
38. Coding With ARC Rules
What is forbidden ?
What can be done but with care ?
What is mandatory ?
Pragma Night
39. Rule 01/12
• Forget about using retain, release,
retainCount and autorelease
{
id obj1 = [[NSObject alloc] init];
/* ... */
[obj1 release];
}
error: ARC forbids explicit message send of 'release'
[obj release];
Pragma Night
40. Rule 02/12
• Forget about using NSAllocateObject,
NSDeallocateObject, NSZone & Co.
/* NSObject.h */
/***********!
Object Allocation / Deallocation! *******/
!
FOUNDATION_EXPORT id
NSAllocateObject(Class, NSUInteger, NSZone *)
NS_AUTOMATED_REFCOUNT_UNAVAILABLE;
error: 'NSAllocateObject' is unavailable:
not available in automatic reference counting mode
Pragma Night
41. Rule 03/12
• Forget about using NSAutoreleasePool
Use @autoreleasepool { ... } Instead
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
/* ... */
[pool drain]; // [pool release];
error: 'NSAutoreleasePool' is unavailable:
not available in automatic reference counting mode
Pragma Night
42. Rule 04/12
• Forget about calling super dealloc
explicitly
- (void) dealloc
{
free(buffer);
[super dealloc];
}
error: ARC forbids explicit message send of 'dealloc'
[super dealloc]; not available in automatic reference counting mode
Pragma Night
43. Rule 05/12
• Object Type Variables Cannot Be
Members of struct or union in C
struct Data
{
NSMutableArray *array;
};
error: ARC forbids Objective-C objs in structs or unions
NSMutableArray *array;
Pragma Night
44. Rule 06/12
• Exceptions use must be exceptional
• For performance purpose, ARC code leaks on exceptions
• In Obj-C ARC is not exception-safe for normal releases by default
• -fobjc-arc-exceptions / -fno-objc-arc-exceptions: enable / disable
• In Obj-C++ -fobjc-arc-exceptions is enabled by default
Pragma Night
45. Rule 07/12
• IBOutlet must be declared as weak
• Outlets should be defined as declared properties
• Outlets should generally be weak
• Top-level objects (or, in iOS, a storyboard scene) should be strong
Resource Programming Guide
Pragma Night
46. Rule 08/12
• Be careful with performSelector
#pragma clang diagnostic push
#pragma clang diagnostic ignored
"-Warc-performSelector-leaks"
[self performSelector:@selector(someMethod)];
#pragma clang diagnostic pop
Pragma Night
47. Rule 09/12
• Follow the naming rule for methods related
to object creation: implicit retained set
• If begins { alloc/new/copy/mutableCopy }, the caller has ownership
• If begins { init }, the method has to: *
• be an instance method
• return an object of type ‘id’ or an object of type of its [super|sub]class
• return an object not registered in autoreleasepool: the caller has ownership
- (id)init...;
* A special case: “ + (void) initialize ”
Pragma Night
48. False Positive
-(NSString*) copyRightString;
-(NSString*) copyRightString NS_RETURNS_NOT_RETAINED;
• NS_RETURNS_RETAINED
• NS_RETURNS_NOT_RETAINED
This macro is ONLY to be used in exceptional circumstances, not to
annotate functions which conform to the Cocoa naming rules.
Pragma Night
49. Rule 10/12
• Switch cases must be wrapped in scope
with { ... }
switch (value)
{
case 0:
{
NSObject *obj= [[NSObject alloc] init];
NSLog(@"obj for value 0: %@", obj);
}
break;
}
Pragma Night
50. Rule 11/12
• The old style singleton which redefines
retain and release is not ARC compatible
• Singletons should be redefined with
dispatch_once
static Foo *sharedInstance;
+ (id)sharedInstance {
static dispatch_once_t predicate;
dispatch_once(&predicate, ^{
sharedInstance = [[Foo alloc] init];
});
return sharedInstance;
}
Pragma Night
51. Rule 12/12
• 'id' and 'void *' Have to Be Cast Explicitly
id object = [[NSObject alloc] init];
void *pointer = object;
Error: implicit conversion of a non-Objective-C pointer type 'void *'
to 'id' is disallowed with ARC
Pragma Night
52. ( _bridge cast )
id object1 = [[NSObject alloc] init];
void *pointer = (__bridge void *)object1;
id object2 = (__bridge id)pointer;
• More dangerous than an __unsafe_unretained
qualified variable !
• You have to manage ownership of the object
yourself carefully or it crashes
Pragma Night
53. ( __bridge_retained cast )
/* ARC */
id object = [[NSObject alloc] init];
void *pointer = (__bridge_retained void *)object;
/* not-ARC */
id object = [[NSObject alloc] init];
void *pointer = object;
[(id)pointer retain];
• From ARC to Core Foundation
• __bridge_retained cast will retain the object just
after the assignment is done
Pragma Night
54. ( __bridge_transfer cast )
/* ARC */
void *pointer = &bytes;
id object = (__bridge_transfer id)pointer;
/* not-ARC */
id object = (id)pointer;
[object retain];
[(id)pointer release];
• From Core Foundation to ARC
• __bridge_transfer cast will release the object just
after the assignment is done
Pragma Night
55. Toll-Free Bridging
/* NSObject.h */
// After using a CFBridgingRetain on an NSObject, the caller
// must take responsibility for calling CFRelease at an
// appropriate time
NS_INLINE CF_RETURNS_RETAINED CFTypeRef
CFBridgingRetain(id X)
{
return (__bridge_retained CFTypeRef)X;
}
NS_INLINE id
CFBridgingRelease(CFTypeRef CF_CONSUMED X)
{
return (__bridge_transfer id)X;
}
Pragma Night
56. ARC MACRO
// define some LLVM3 macros if the code is
// compiled with a different compiler (ie LLVMGCC42)
#ifndef __has_ feature
#define __has_feature(x) 0
#endif
#ifndef __has_extension
// Compatibility with pre-3.0 compilers
#define __has_extension __has_feature
#endif
#if __has_feature(objc_arc) && __clang_major__ >= 3
#define ARC_ENABLED 1
#endif
Check @ compile-time if ARC is enabled
Pragma Night
57. tl;dr What Is ARC ?
• Automatic memory management of Obj-C objects
• Compiler obeys and enforces existing conventions
• Full interoperability with manual retain and release
• New runtime features
• Weak pointers
• Advanced performance optimizations
Pragma Night
58. tl;dr What ARC Is NOT ?
• No new runtime memory model
• No automation for malloc/free, CF, etc.
• No garbage collector
• No heap scans
• No whole app pauses
• No non-deterministic releases
Pragma Night
59. ARC References
• Clang: Automatic Reference Counting documentation
• Apple: Transitioning to ARC Release Notes
• Apple: Xcode New Features User Guide: Automatic Reference Counting
• WWDC 2011 – Session 323 – Introducing Automatic Reference Counting
• WWDC 2012 – Session 406/416 – Adopting Automatic Reference Counting
• Mike Ash: Friday Q&A about Automatic Reference Counting
• Mike Ash: Zeroing weak references without ARC
Pragma Night