SlideShare ist ein Scribd-Unternehmen logo
1 von 58
Downloaden Sie, um offline zu lesen
Objective C/C++

  Работа с памятью без
использования Instruments
Memory and resource management

LOCAL OBJECTS
C
• System language
• Portable assembler
C
• Memory management - C example
  static bool check_memory()
  {
  !   Something * a = (Something *)malloc( sizeof(Something) );
  !   if( !a )
  !   !    return false;
  !   do_something(a);
  !   if( some_condition(a) )
  !   {
  !   !    free(a);
  !   !    return true;
  !   }
  !   // Lots of code
  !   free(a);
  !   return false;
  }
C
• Resource management - C example
  static bool check_file(const char * name)
  {
  !   FILE * fs = fopen(name, "rb");
  !   if( !fs )
  !   !    return false;
  !   int first = fgetc(fs);
  !   if( first == 32 )
  !   {
  !   !    fclose(fs);
  !   !    return true;
  !   }
  !   // Lots of code
  !   fclose(fs);
  !   return false;
  }
C
• Resource management - C example
  static bool check_file(const char * name)
  {
  !   FILE * fs = fopen(name, "rb");
  !   if( !fs )
  !   !    return false;
  !   int first = fgetc(fs);
  !   if( first == 32 )
  !   {
  !   !    fclose(fs);
  !   !    return true;
  !   }
  !   // Lots of code
  !   fclose(fs);
  !   return false;
  }
Java
• Memory management example
     static public boolean check_memory()
 	   {
 	   	   Something a = new Something();
 	   	   a.do_something();
 	   	   if( a.some_condition() )
 	   	   	   return true;
 	   	   // Lots of code
 	   	   return false;
 	   }
Java
• Resource management example
     static public boolean check_file(String name) throws Exception
 	   {
 	   	   FileInputStream fs = new FileInputStream(name);
 	   	   int first = fs.read();
 	   	   if( first == 32 )
 	   	   	   return true;
 	   	   // Lots of code
 	   	   return false;
 	   }
Java
• Resource management example
     static public boolean check_file(String name) throws Exception
 	   {
 	   	   FileInputStream fs = new FileInputStream(name);
 	   	   int first = fs.read();
 	   	   if( first == 32 )
 	   	   	   return true;
 	   	   // Lots of code
 	   	   return false;
 	   }
 	   static public void delete_if_bad(String name) throws Exception
 	   {
 	   	   if( !check_file(name) )
 	   	   	   new java.io.File(name).delete();
 	   }
Java
• Resource management - with finally
 	   static public boolean check_file2(String name) throws Exception
 	   {
 	   	   FileInputStream fs = null;
 	   	   try
 	   	   {
 	   	   	   fs = new FileInputStream(name);
 	   	   	   int first = fs.read();
 	   	   	   if( first == 32 )
 	   	   	   	   return true;
 	   	   	   // Lots of code
 	   	   	   return false;
 	   	   }
 	   	   finally{
 	   	   	   if( fs != null )
 	   	   	   	   fs.close();
 	   	   }
 	   }
Java
• Resource management - with catch
 	   static public boolean check_file3(String name) throws Exception
 	   {
 	   	    FileInputStream fs = null;
 	   	    try
 	   	    {
 	   	    	     fs = new FileInputStream(name);
 	   	    	     int first = fs.read();
 	   	    	     if( first == 32 )
 	   	    	     	    return true;
 	   	    	     // Lots of code
 	   	    }
 	   	    catch(Exception e)
 	   	    {}
 	   	    try {
 	   	    	     if( fs != null )
 	   	    	     	    fs.close();
 	   	    }
 	   	    catch(Exception e)
 	   	    {}
 	   	    return false;
 	   }
C#
• Memory management example
     static public bool check_memory()
 	   {
 	   	   Something a = new Something();
 	   	   a.do_something();
 	   	   if( a.some_condition() )
 	   	   	   return true;
 	   	   // Lots of code
 	   	   return false;
 	   }
C#
• Resource management example
     static public bool check_file(String name)
 	   {
 	   	   using( FileInputStream fs = new FileInputStream(name) )
         {
     	   	   int first = fs.read();
     	   	   if( first == 32 )
     	   	   	   return true;
     	   	   // Lots of code
         }
 	   	   return false;
 	   }
C++
• System language
• Life without garbage collector?
• Unique semantic!
C++
• Memory management - what C
  developer thinks?
• If I know C I already know C++!
   static bool check_memory()
   {
   !   Something * a = new Something;
   !   if( !a )
   !   !    return false;
   !   a->do_something();
   !   if( a->some_condition() )
   !   {
   !   !    delete a;
   !   !    return true;
   !   }
   !   // Lots of code
   !   delete a;
   !   return false;
   }
C++
• Memory management - what C
  developer thinks?
• If I know C I already know C++!
   static bool check_memory()
   {
   !   Something * a = (Something *)malloc( sizeof(Something) );
   !   if( !a )
   !   !    return false;
   !   do_something(a);
   !   if( some_condition(a) )
   !   {
   !   !    free(a);
   !   !    return true;
   !   }
   !   // Lots of code
   !   free(a);
   !   return false;
   }
C++
•   Are there exceptions in C++?
•   Are they good or evil? Good!
•   If I do not use them?
•   You are allowed not to throw
•   But good C++ design always uses
    exceptions, so you better be prepared
C++
• Memory management example
  static bool check_memory()
  {
  !   std::auto_ptr<Something> a( new Something );
  !   a->do_something();
  !   if( a->some_condition() )
  !   !    return true;
  !   // Lots of code
  !   return false;
  }
C++
• Resource management example
  static bool check_file(const std::string & name)
  {
  !   liba::FileInputStream fs(name);
  !   int first = fs.read();
  !   if( first == 32 )
  !   !    return true;
  !   // Lots of code
  !   return false;
  }
C++
• Resource management example
  static bool check_file(const std::string & name)
  {
  !   std::auto_ptr<liba::FileInputStream> fs( liba::create_fis(name) );
  !   int first = fs->read();
  !   if( first == 32 )
  !   !    return true;
  !   // Lots of code
  !   return false;
  }
C++
• Delete is for implementing libraries!
 {
 	   std::auto_ptr<Something> a( new Something(...) );
 	
 	   if( ... )
 	   	    return;
 }



• No difference between memory and
  other resource types
Objective-C
• Memory management - what C
  developer thinks?
• If I know C I already know Objective-C!
   -(bool)check_memory
   {
   !   Something * a = [[Something alloc] init];
   !   if( !a )
   !   !    return false;
   !   [a do_something];
   !   if( [a some_condition] )
   !   {
   !   !    [a release];
   !   !    return true;
   !   }
   !   // Lots of code
   !   [a release];
   !   return false;
   }
Objective-C
• Memory management - what C
  developer thinks?
• If I know C I already know Objective-C!
   static bool check_memory()
   {
   !   Something * a = (Something *)malloc( sizeof(Something) );
   !   if( !a )
   !   !    return false;
   !   do_something(a);
   !   if( some_condition(a) )
   !   {
   !   !    free(a);
   !   !    return true;
   !   }
   !   // Lots of code
   !   free(a);
   !   return false;
   }
Objective-C
• Are there exceptions in Objective-C?
• Are they good or evil? Absolutely good!
   -(void)parse_object:(NSDictionary *)dic {
   !   // Lots of code
   !   int val = [[[dic objectForKey:@"users"] objectAtIndex:0] intValue];
   !   // Lots of code
   }

   -(void)parse_object:(NSDictionary *)dic {
   !   // Lots of code
   !   NSArray * arr = [dic objectForKey:@"users"];
   !   if( ![arr isKindOfClass:[NSArray class]] )
   !   !    return; // But we must tell about error...
   !   NSNumber * num = [arr objectAtIndex:0];
   !   if( ![num isKindOfClass:[NSNumber class]] )
   !   !    return; // But we must tell about error...
   !   int val = [num intValue];
   !   // Lots of code
   }
Objective-C
• Memory management example
 -(bool)check_memory
 {
 !   Something * a = [[[Something alloc] init] autorelease];
 !   [a do_something];
 !   if( [a some_condition] )
 !   !    return true;
 !   // Lots of code
 !   return false;
 }
Objective-C
• Memory management example
  -(bool)check_memory
  {
  !   Something * a = [[[Something alloc] init] autorelease];
  !   [a do_something];
  !   if( [a some_condition] )
  !   !    return true;
  !   // Lots of code
  !   return false;
  }




• Afraid of autorelease?
• Just start using it!
• It is widely used in Cocoa
Memory and resource management

LONG-LIVED OBJECTS
Approaches




Garbage collector   Ownership graph
Approaches
• It takes lots of CPU time to untangle this!
Approaches
• You must prove the graph is acyclic!
Approaches
• What is more scary than memory leak?
Approaches
• What is more scary than memory leak?
• Dangling pointer!
Objective-C
• Retaining
  @interface Something : NSObject {
  !   Anything * a;
  }

  @end

  @implementation Something

  -(void)do_something {
  !   Anything * new_a = [[[Anything alloc] init] autorelease];

  !   [a release]; // [a autorelease];
  !   a = [new_a retain];
  }

  -(void)dealloc {
  !   [a release];
  !   [super dealloc];
  }

  @end
Objective-C
• Retaining
  @interface Something : NSObject {
  !   Anything * a;
  }
  @property(nonatomic, retain) Anything * a;

  @end

  @implementation Something
  @synthesize a;

  -(void)do_something {
  !   Anything * new_a = [[[Anything alloc] init] autorelease];

  !   self.a = new_a;
  }

  -(void)dealloc {
  !   self.a = 0;
  !   [super dealloc];
  }

  @end
Objective-C
• Subtle differences
  !   self.a = new_a; // Call property
  !   self->a = new_a; // Use variable
  !   a = new_a; // ???
Objective-C
• Subtle differences
  @interface Something : NSObject {
  !   Anything * a_zlo_hren;
  }
  @property(nonatomic, retain) Anything * a;

  @end

  @implementation Something
  @synthesize a = a_zlo_hren;

  -(void)do_something {
  !   Anything * new_a = [[[Anything alloc] init] autorelease];

  !   self.a = new_a; // Call property
  !   self->a = new_a; // Use variable
  !   a = new_a; // ???
  }
Objective-C
• 4 lines to free the memory? Too much.
     Anything * a_zlo_hren;

 @property(nonatomic, retain) Anything * a;

 @synthesize a = a_zlo_hren;

 !   self.a = 0; // In dealloc
Objective-C++
• Objective C is also C++
  @interface Something : NSObject {
  !   NSPtr<Anything> a;
  }

  @end

  @implementation Something

  -(void)do_something {
  !   Anything * new_a = [[[Anything alloc] init] autorelease];

  !   a = new_a;
  }

  @end



• 4 lines go down to 1, good!
Objective-C++
• Retain cycles
  @interface Something : NSObject {
  !   Anything * a;
  }
  @property(nonatomic, retain) Anything * a;

  @end

  @interface Anything : NSObject {
  !   Something * s;
  }
  @property(nonatomic, retain) Something * s;

  @end
Objective-C++
• Retain cycles
  @interface Something : NSObject {
  !   Anything * a;
  }
  @property(nonatomic, retain) Anything * a;

  @end

  @interface Anything : NSObject {
  !   Something * s;
  }
  @property(nonatomic, retain) Something * s;

  @end
Objective-C++
• Retain cycles
  @interface Something : NSObject {
  !   Anything * a;
  }
  @property(nonatomic, retain) Anything * a;

  @end

  @interface Anything : NSObject {
  !   Something * s;
  }

  @end
Retain cycles
• Can compiler find them?

• Can runtime find them?

• Can tools find them?

• Is there a simple approach to avoid
  them?
Retain cycles
• Can compiler find them?
Yes, soon (experimental languages).
• Can runtime find them?

• Can tools find them?

• Is there a simple approach to avoid
  them?
Retain cycles
• Can compiler find them?
Yes, soon (experimental languages).
• Can runtime find them?
Yes, Garbage Collector.
• Can tools find them?

• Is there a simple approach to avoid
  them?
Retain cycles
• Can compiler find them?
Yes, soon (experimental languages).
• Can runtime find them?
Yes, Garbage Collector.
• Can tools find them?
Yes, if included in test cases.
• Is there a simple approach to avoid
  them?
Retain cycles
• Can compiler find them?
Yes, soon (experimental languages).
• Can runtime find them?
Yes, Garbage Collector.
• Can tools find them?
Yes, if included in test cases.
• Is there a simple approach to avoid
  them?
Yes, analyze architecture.
Objective-C
• Containers always retain
  @interface Something : NSObject {
  !   NSMutableArray * a;
  }
  @property(nonatomic, retain) NSMutableArray * a;

  @end


  -(void)do_something {
  !   Anything * new_a = [[[Anything alloc] init] autorelease];
  !   Anything * new_a2 = [[[Anything alloc] init] autorelease];

  !   [a addObject:new_a];
  !   [a addObject:new_a2];
  }
Objective-C
• If we do not want to retain?
  @interface Something : NSObject {
  !   NSMutableArray * a;
  }
  @property(nonatomic, retain) NSMutableArray * a;

  @end


  -(void)do_something {
  !   Anything * new_a = [[[Anything alloc] init] autorelease];
  !   Anything * new_a2 = [[[Anything alloc] init] autorelease];

  !   [a addObject:[NSValue valueWithNonretainedObject:new_a]];
  !   [a addObject:[NSValue valueWithNonretainedObject:new_a2]];
  }

  -(void)use_something {
  !   Anything * aa = [[a objectAtIndex:0] nonretainedObjectValue];
  }
Objective-C
• What if we retain by accident?
  @interface Something : NSObject {
  !   NSMutableArray * a;
  }
  @property(nonatomic, retain) NSMutableArray * a;

  @end


  -(void)do_something {
  !   Anything * new_a = [[[Anything alloc] init] autorelease];
  !   Anything * new_a2 = [[[Anything alloc] init] autorelease];

  !   [a addObject:new_a]; // Someone forgot
  !   [a addObject:new_a2]; // Someone forgot
  }
Objective-C
• Containers are untyped
 @interface Something : NSObject {
 !   NSMutableArray * a; // Of Anything
 }
 @property(nonatomic, retain) NSMutableArray * a; // Of Anything

 @end


 -(void)do_something {
 !   Anything * new_a = [[[Anything alloc] init] autorelease];
 !   Anything * new_a2 = [[[Anything alloc] init] autorelease];

 !   [a addObject:new_a];
 !   [a addObject:new_a2];
 }
Objective-C
• Untyped containers are hard to prove
  @interface Something : NSObject {
  !   NSMutableArray * a; // Of Anything
  }
  @property(nonatomic, retain) NSMutableArray * a; // Of Anything

  @end


  -(void)do_something {
  !   Anything * new_a = [[[Anything alloc] init] autorelease];
  !   NSString * str = @"Hi";

  !   [a addObject:new_a];
  !   [a addObject:str];
  }
Objective-C++
• We can use great STL containers
  @interface Something : NSObject {
  !   std::vector<Anything *> a;
  }

  @end



  -(void)do_something {
  !   Anything * new_a = [[[Anything alloc] init] autorelease];
  !   NSString * str = @"Hi";

  !   a.push_back( new_a );
  !   a.push_back( str );
  }
Objective-C++
• Retain strategy is independent
  @interface Something : NSObject {
  !   std::vector< NSPtr<Anything> > a;
  }

  @end



  -(void)do_something {
  !   Anything * new_a = [[[Anything alloc] init] autorelease];
  !   NSString * str = @"Hi";

  !   a.push_back( new_a );
  !   a.push_back( str );
  }
Objective-C++
• Integration is almost flawless!
• Apple teams actually use C++ and STL
 @interface Something : NSObject {
 !   std::vector< id<UIActionSheetDelegate> > a;
 }

 @end


 -(void)do_something {
 !   std::for_each(a.begin(), a.end(), ^(id<UIActionSheetDelegate> x) {
 !   !    [x actionSheetCancel:nil];
 !   });
 }
Success
• alloc-init-autorelease idiom
• NSPtr or @property(retain) to manage
  retain/release
• Use text editor to eliminate all retain,
  release
• Architecture with no cycles
• Typed containers (STL), so the compiler
  can actually prove most of your
  architecture
What we forgot?
• Active objects (timers, http requests)
• Parallel execution (NSOperation)
What we forgot?
• Active objects (timers, http requests)
• Parallel execution (NSOperation)


         Do not worry!
        This is also easy!
Q&A




                  Q&A
Grigory Buteyko
hrissan@mail.ru
www.dataart.com

Weitere ähnliche Inhalte

Was ist angesagt?

Cluj.py Meetup: Extending Python in C
Cluj.py Meetup: Extending Python in CCluj.py Meetup: Extending Python in C
Cluj.py Meetup: Extending Python in CSteffen Wenz
 
Simple ETL in python 3.5+ with Bonobo - PyParis 2017
Simple ETL in python 3.5+ with Bonobo - PyParis 2017Simple ETL in python 3.5+ with Bonobo - PyParis 2017
Simple ETL in python 3.5+ with Bonobo - PyParis 2017Romain Dorgueil
 
EuroPython 2016 - Do I Need To Switch To Golang
EuroPython 2016 - Do I Need To Switch To GolangEuroPython 2016 - Do I Need To Switch To Golang
EuroPython 2016 - Do I Need To Switch To GolangMax Tepkeev
 
Minicurso Ruby e Rails
Minicurso Ruby e RailsMinicurso Ruby e Rails
Minicurso Ruby e RailsSEA Tecnologia
 
Basic file operations CBSE class xii ln 7
Basic file operations CBSE class xii  ln 7Basic file operations CBSE class xii  ln 7
Basic file operations CBSE class xii ln 7SATHASIVAN H
 
Javascript engine performance
Javascript engine performanceJavascript engine performance
Javascript engine performanceDuoyi Wu
 
Apache PIG - User Defined Functions
Apache PIG - User Defined FunctionsApache PIG - User Defined Functions
Apache PIG - User Defined FunctionsChristoph Bauer
 
Virtual machine and javascript engine
Virtual machine and javascript engineVirtual machine and javascript engine
Virtual machine and javascript engineDuoyi Wu
 
Powered by Python - PyCon Germany 2016
Powered by Python - PyCon Germany 2016Powered by Python - PyCon Germany 2016
Powered by Python - PyCon Germany 2016Steffen Wenz
 
05 pig user defined functions (udfs)
05 pig user defined functions (udfs)05 pig user defined functions (udfs)
05 pig user defined functions (udfs)Subhas Kumar Ghosh
 
Modern C++ Lunch and Learn
Modern C++ Lunch and LearnModern C++ Lunch and Learn
Modern C++ Lunch and LearnPaul Irwin
 
响应式编程及框架
响应式编程及框架响应式编程及框架
响应式编程及框架jeffz
 
Java 7 JUG Summer Camp
Java 7 JUG Summer CampJava 7 JUG Summer Camp
Java 7 JUG Summer Campjulien.ponge
 
Java 7 at SoftShake 2011
Java 7 at SoftShake 2011Java 7 at SoftShake 2011
Java 7 at SoftShake 2011julien.ponge
 
Euro python2011 High Performance Python
Euro python2011 High Performance PythonEuro python2011 High Performance Python
Euro python2011 High Performance PythonIan Ozsvald
 
Cluj Big Data Meetup - Big Data in Practice
Cluj Big Data Meetup - Big Data in PracticeCluj Big Data Meetup - Big Data in Practice
Cluj Big Data Meetup - Big Data in PracticeSteffen Wenz
 
Python 3000
Python 3000Python 3000
Python 3000Bob Chao
 

Was ist angesagt? (20)

Cluj.py Meetup: Extending Python in C
Cluj.py Meetup: Extending Python in CCluj.py Meetup: Extending Python in C
Cluj.py Meetup: Extending Python in C
 
Simple ETL in python 3.5+ with Bonobo - PyParis 2017
Simple ETL in python 3.5+ with Bonobo - PyParis 2017Simple ETL in python 3.5+ with Bonobo - PyParis 2017
Simple ETL in python 3.5+ with Bonobo - PyParis 2017
 
EuroPython 2016 - Do I Need To Switch To Golang
EuroPython 2016 - Do I Need To Switch To GolangEuroPython 2016 - Do I Need To Switch To Golang
EuroPython 2016 - Do I Need To Switch To Golang
 
Minicurso Ruby e Rails
Minicurso Ruby e RailsMinicurso Ruby e Rails
Minicurso Ruby e Rails
 
Basic file operations CBSE class xii ln 7
Basic file operations CBSE class xii  ln 7Basic file operations CBSE class xii  ln 7
Basic file operations CBSE class xii ln 7
 
Javascript engine performance
Javascript engine performanceJavascript engine performance
Javascript engine performance
 
Apache PIG - User Defined Functions
Apache PIG - User Defined FunctionsApache PIG - User Defined Functions
Apache PIG - User Defined Functions
 
Virtual machine and javascript engine
Virtual machine and javascript engineVirtual machine and javascript engine
Virtual machine and javascript engine
 
Powered by Python - PyCon Germany 2016
Powered by Python - PyCon Germany 2016Powered by Python - PyCon Germany 2016
Powered by Python - PyCon Germany 2016
 
Intro to Pig UDF
Intro to Pig UDFIntro to Pig UDF
Intro to Pig UDF
 
05 pig user defined functions (udfs)
05 pig user defined functions (udfs)05 pig user defined functions (udfs)
05 pig user defined functions (udfs)
 
Modern C++ Lunch and Learn
Modern C++ Lunch and LearnModern C++ Lunch and Learn
Modern C++ Lunch and Learn
 
响应式编程及框架
响应式编程及框架响应式编程及框架
响应式编程及框架
 
Java 7 JUG Summer Camp
Java 7 JUG Summer CampJava 7 JUG Summer Camp
Java 7 JUG Summer Camp
 
Java 7 at SoftShake 2011
Java 7 at SoftShake 2011Java 7 at SoftShake 2011
Java 7 at SoftShake 2011
 
Euro python2011 High Performance Python
Euro python2011 High Performance PythonEuro python2011 High Performance Python
Euro python2011 High Performance Python
 
Cluj Big Data Meetup - Big Data in Practice
Cluj Big Data Meetup - Big Data in PracticeCluj Big Data Meetup - Big Data in Practice
Cluj Big Data Meetup - Big Data in Practice
 
C++ Advanced Features
C++ Advanced FeaturesC++ Advanced Features
C++ Advanced Features
 
C++ Advanced Features
C++ Advanced FeaturesC++ Advanced Features
C++ Advanced Features
 
Python 3000
Python 3000Python 3000
Python 3000
 

Ähnlich wie Objective-c memory

Øredev 2011 - JVM JIT for Dummies (What the JVM Does With Your Bytecode When ...
Øredev 2011 - JVM JIT for Dummies (What the JVM Does With Your Bytecode When ...Øredev 2011 - JVM JIT for Dummies (What the JVM Does With Your Bytecode When ...
Øredev 2011 - JVM JIT for Dummies (What the JVM Does With Your Bytecode When ...Charles Nutter
 
Blocks & GCD
Blocks & GCDBlocks & GCD
Blocks & GCDrsebbe
 
Dynamic memory allocation
Dynamic memory allocationDynamic memory allocation
Dynamic memory allocationViji B
 
Javascript Everywhere
Javascript EverywhereJavascript Everywhere
Javascript EverywherePascal Rettig
 
CodiLime Tech Talk - Grzegorz Rozdzialik: What the java script
CodiLime Tech Talk - Grzegorz Rozdzialik: What the java scriptCodiLime Tech Talk - Grzegorz Rozdzialik: What the java script
CodiLime Tech Talk - Grzegorz Rozdzialik: What the java scriptCodiLime
 
JavaOne 2012 - JVM JIT for Dummies
JavaOne 2012 - JVM JIT for DummiesJavaOne 2012 - JVM JIT for Dummies
JavaOne 2012 - JVM JIT for DummiesCharles Nutter
 
Memory Management with Java and C++
Memory Management with Java and C++Memory Management with Java and C++
Memory Management with Java and C++Mohammad Shaker
 
Application-Specific Models and Pointcuts using a Logic Meta Language
Application-Specific Models and Pointcuts using a Logic Meta LanguageApplication-Specific Models and Pointcuts using a Logic Meta Language
Application-Specific Models and Pointcuts using a Logic Meta LanguageESUG
 
Explaining ES6: JavaScript History and What is to Come
Explaining ES6: JavaScript History and What is to ComeExplaining ES6: JavaScript History and What is to Come
Explaining ES6: JavaScript History and What is to ComeCory Forsyth
 
DotNetFest - Let’s refresh our memory! Memory management in .NET
DotNetFest - Let’s refresh our memory! Memory management in .NETDotNetFest - Let’s refresh our memory! Memory management in .NET
DotNetFest - Let’s refresh our memory! Memory management in .NETMaarten Balliauw
 
JavaScript in 2016
JavaScript in 2016JavaScript in 2016
JavaScript in 2016Codemotion
 
JavaScript in 2016 (Codemotion Rome)
JavaScript in 2016 (Codemotion Rome)JavaScript in 2016 (Codemotion Rome)
JavaScript in 2016 (Codemotion Rome)Eduard Tomàs
 
JavaScript for Web Analysts
JavaScript for Web AnalystsJavaScript for Web Analysts
JavaScript for Web AnalystsLukáš Čech
 

Ähnlich wie Objective-c memory (20)

Øredev 2011 - JVM JIT for Dummies (What the JVM Does With Your Bytecode When ...
Øredev 2011 - JVM JIT for Dummies (What the JVM Does With Your Bytecode When ...Øredev 2011 - JVM JIT for Dummies (What the JVM Does With Your Bytecode When ...
Øredev 2011 - JVM JIT for Dummies (What the JVM Does With Your Bytecode When ...
 
Go Memory
Go MemoryGo Memory
Go Memory
 
Go memory
Go memoryGo memory
Go memory
 
Blocks & GCD
Blocks & GCDBlocks & GCD
Blocks & GCD
 
Dynamic memory allocation
Dynamic memory allocationDynamic memory allocation
Dynamic memory allocation
 
dynamic-allocation.pdf
dynamic-allocation.pdfdynamic-allocation.pdf
dynamic-allocation.pdf
 
Javascript Everywhere
Javascript EverywhereJavascript Everywhere
Javascript Everywhere
 
CodiLime Tech Talk - Grzegorz Rozdzialik: What the java script
CodiLime Tech Talk - Grzegorz Rozdzialik: What the java scriptCodiLime Tech Talk - Grzegorz Rozdzialik: What the java script
CodiLime Tech Talk - Grzegorz Rozdzialik: What the java script
 
JavaOne 2012 - JVM JIT for Dummies
JavaOne 2012 - JVM JIT for DummiesJavaOne 2012 - JVM JIT for Dummies
JavaOne 2012 - JVM JIT for Dummies
 
Core java
Core javaCore java
Core java
 
Why learn Internals?
Why learn Internals?Why learn Internals?
Why learn Internals?
 
Memory Management with Java and C++
Memory Management with Java and C++Memory Management with Java and C++
Memory Management with Java and C++
 
Application-Specific Models and Pointcuts using a Logic Meta Language
Application-Specific Models and Pointcuts using a Logic Meta LanguageApplication-Specific Models and Pointcuts using a Logic Meta Language
Application-Specific Models and Pointcuts using a Logic Meta Language
 
Es.next
Es.nextEs.next
Es.next
 
Explaining ES6: JavaScript History and What is to Come
Explaining ES6: JavaScript History and What is to ComeExplaining ES6: JavaScript History and What is to Come
Explaining ES6: JavaScript History and What is to Come
 
DotNetFest - Let’s refresh our memory! Memory management in .NET
DotNetFest - Let’s refresh our memory! Memory management in .NETDotNetFest - Let’s refresh our memory! Memory management in .NET
DotNetFest - Let’s refresh our memory! Memory management in .NET
 
JavaScript in 2016
JavaScript in 2016JavaScript in 2016
JavaScript in 2016
 
JavaScript in 2016 (Codemotion Rome)
JavaScript in 2016 (Codemotion Rome)JavaScript in 2016 (Codemotion Rome)
JavaScript in 2016 (Codemotion Rome)
 
JavaScript for Web Analysts
JavaScript for Web AnalystsJavaScript for Web Analysts
JavaScript for Web Analysts
 
Introduction to c part -3
Introduction to c   part -3Introduction to c   part -3
Introduction to c part -3
 

Kürzlich hochgeladen

Event-Driven Architecture Masterclass: Challenges in Stream Processing
Event-Driven Architecture Masterclass: Challenges in Stream ProcessingEvent-Driven Architecture Masterclass: Challenges in Stream Processing
Event-Driven Architecture Masterclass: Challenges in Stream ProcessingScyllaDB
 
Intro to Passkeys and the State of Passwordless.pptx
Intro to Passkeys and the State of Passwordless.pptxIntro to Passkeys and the State of Passwordless.pptx
Intro to Passkeys and the State of Passwordless.pptxFIDO Alliance
 
ChatGPT and Beyond - Elevating DevOps Productivity
ChatGPT and Beyond - Elevating DevOps ProductivityChatGPT and Beyond - Elevating DevOps Productivity
ChatGPT and Beyond - Elevating DevOps ProductivityVictorSzoltysek
 
2024 May Patch Tuesday
2024 May Patch Tuesday2024 May Patch Tuesday
2024 May Patch TuesdayIvanti
 
Choreo: Empowering the Future of Enterprise Software Engineering
Choreo: Empowering the Future of Enterprise Software EngineeringChoreo: Empowering the Future of Enterprise Software Engineering
Choreo: Empowering the Future of Enterprise Software EngineeringWSO2
 
WebRTC and SIP not just audio and video @ OpenSIPS 2024
WebRTC and SIP not just audio and video @ OpenSIPS 2024WebRTC and SIP not just audio and video @ OpenSIPS 2024
WebRTC and SIP not just audio and video @ OpenSIPS 2024Lorenzo Miniero
 
Introduction to FIDO Authentication and Passkeys.pptx
Introduction to FIDO Authentication and Passkeys.pptxIntroduction to FIDO Authentication and Passkeys.pptx
Introduction to FIDO Authentication and Passkeys.pptxFIDO Alliance
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Victor Rentea
 
Decarbonising Commercial Real Estate: The Role of Operational Performance
Decarbonising Commercial Real Estate: The Role of Operational PerformanceDecarbonising Commercial Real Estate: The Role of Operational Performance
Decarbonising Commercial Real Estate: The Role of Operational PerformanceIES VE
 
Tales from a Passkey Provider Progress from Awareness to Implementation.pptx
Tales from a Passkey Provider  Progress from Awareness to Implementation.pptxTales from a Passkey Provider  Progress from Awareness to Implementation.pptx
Tales from a Passkey Provider Progress from Awareness to Implementation.pptxFIDO Alliance
 
Continuing Bonds Through AI: A Hermeneutic Reflection on Thanabots
Continuing Bonds Through AI: A Hermeneutic Reflection on ThanabotsContinuing Bonds Through AI: A Hermeneutic Reflection on Thanabots
Continuing Bonds Through AI: A Hermeneutic Reflection on ThanabotsLeah Henrickson
 
WSO2 Micro Integrator for Enterprise Integration in a Decentralized, Microser...
WSO2 Micro Integrator for Enterprise Integration in a Decentralized, Microser...WSO2 Micro Integrator for Enterprise Integration in a Decentralized, Microser...
WSO2 Micro Integrator for Enterprise Integration in a Decentralized, Microser...WSO2
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityWSO2
 
Simplifying Mobile A11y Presentation.pptx
Simplifying Mobile A11y Presentation.pptxSimplifying Mobile A11y Presentation.pptx
Simplifying Mobile A11y Presentation.pptxMarkSteadman7
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Victor Rentea
 
Portal Kombat : extension du réseau de propagande russe
Portal Kombat : extension du réseau de propagande russePortal Kombat : extension du réseau de propagande russe
Portal Kombat : extension du réseau de propagande russe中 央社
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDropbox
 
ERP Contender Series: Acumatica vs. Sage Intacct
ERP Contender Series: Acumatica vs. Sage IntacctERP Contender Series: Acumatica vs. Sage Intacct
ERP Contender Series: Acumatica vs. Sage IntacctBrainSell Technologies
 

Kürzlich hochgeladen (20)

Event-Driven Architecture Masterclass: Challenges in Stream Processing
Event-Driven Architecture Masterclass: Challenges in Stream ProcessingEvent-Driven Architecture Masterclass: Challenges in Stream Processing
Event-Driven Architecture Masterclass: Challenges in Stream Processing
 
Intro to Passkeys and the State of Passwordless.pptx
Intro to Passkeys and the State of Passwordless.pptxIntro to Passkeys and the State of Passwordless.pptx
Intro to Passkeys and the State of Passwordless.pptx
 
ChatGPT and Beyond - Elevating DevOps Productivity
ChatGPT and Beyond - Elevating DevOps ProductivityChatGPT and Beyond - Elevating DevOps Productivity
ChatGPT and Beyond - Elevating DevOps Productivity
 
2024 May Patch Tuesday
2024 May Patch Tuesday2024 May Patch Tuesday
2024 May Patch Tuesday
 
Choreo: Empowering the Future of Enterprise Software Engineering
Choreo: Empowering the Future of Enterprise Software EngineeringChoreo: Empowering the Future of Enterprise Software Engineering
Choreo: Empowering the Future of Enterprise Software Engineering
 
WebRTC and SIP not just audio and video @ OpenSIPS 2024
WebRTC and SIP not just audio and video @ OpenSIPS 2024WebRTC and SIP not just audio and video @ OpenSIPS 2024
WebRTC and SIP not just audio and video @ OpenSIPS 2024
 
Introduction to FIDO Authentication and Passkeys.pptx
Introduction to FIDO Authentication and Passkeys.pptxIntroduction to FIDO Authentication and Passkeys.pptx
Introduction to FIDO Authentication and Passkeys.pptx
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
Decarbonising Commercial Real Estate: The Role of Operational Performance
Decarbonising Commercial Real Estate: The Role of Operational PerformanceDecarbonising Commercial Real Estate: The Role of Operational Performance
Decarbonising Commercial Real Estate: The Role of Operational Performance
 
Tales from a Passkey Provider Progress from Awareness to Implementation.pptx
Tales from a Passkey Provider  Progress from Awareness to Implementation.pptxTales from a Passkey Provider  Progress from Awareness to Implementation.pptx
Tales from a Passkey Provider Progress from Awareness to Implementation.pptx
 
Continuing Bonds Through AI: A Hermeneutic Reflection on Thanabots
Continuing Bonds Through AI: A Hermeneutic Reflection on ThanabotsContinuing Bonds Through AI: A Hermeneutic Reflection on Thanabots
Continuing Bonds Through AI: A Hermeneutic Reflection on Thanabots
 
WSO2 Micro Integrator for Enterprise Integration in a Decentralized, Microser...
WSO2 Micro Integrator for Enterprise Integration in a Decentralized, Microser...WSO2 Micro Integrator for Enterprise Integration in a Decentralized, Microser...
WSO2 Micro Integrator for Enterprise Integration in a Decentralized, Microser...
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
 
Simplifying Mobile A11y Presentation.pptx
Simplifying Mobile A11y Presentation.pptxSimplifying Mobile A11y Presentation.pptx
Simplifying Mobile A11y Presentation.pptx
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
Portal Kombat : extension du réseau de propagande russe
Portal Kombat : extension du réseau de propagande russePortal Kombat : extension du réseau de propagande russe
Portal Kombat : extension du réseau de propagande russe
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
ERP Contender Series: Acumatica vs. Sage Intacct
ERP Contender Series: Acumatica vs. Sage IntacctERP Contender Series: Acumatica vs. Sage Intacct
ERP Contender Series: Acumatica vs. Sage Intacct
 

Objective-c memory

  • 1. Objective C/C++ Работа с памятью без использования Instruments
  • 2. Memory and resource management LOCAL OBJECTS
  • 3. C • System language • Portable assembler
  • 4. C • Memory management - C example static bool check_memory() { ! Something * a = (Something *)malloc( sizeof(Something) ); ! if( !a ) ! ! return false; ! do_something(a); ! if( some_condition(a) ) ! { ! ! free(a); ! ! return true; ! } ! // Lots of code ! free(a); ! return false; }
  • 5. C • Resource management - C example static bool check_file(const char * name) { ! FILE * fs = fopen(name, "rb"); ! if( !fs ) ! ! return false; ! int first = fgetc(fs); ! if( first == 32 ) ! { ! ! fclose(fs); ! ! return true; ! } ! // Lots of code ! fclose(fs); ! return false; }
  • 6. C • Resource management - C example static bool check_file(const char * name) { ! FILE * fs = fopen(name, "rb"); ! if( !fs ) ! ! return false; ! int first = fgetc(fs); ! if( first == 32 ) ! { ! ! fclose(fs); ! ! return true; ! } ! // Lots of code ! fclose(fs); ! return false; }
  • 7. Java • Memory management example static public boolean check_memory() { Something a = new Something(); a.do_something(); if( a.some_condition() ) return true; // Lots of code return false; }
  • 8. Java • Resource management example static public boolean check_file(String name) throws Exception { FileInputStream fs = new FileInputStream(name); int first = fs.read(); if( first == 32 ) return true; // Lots of code return false; }
  • 9. Java • Resource management example static public boolean check_file(String name) throws Exception { FileInputStream fs = new FileInputStream(name); int first = fs.read(); if( first == 32 ) return true; // Lots of code return false; } static public void delete_if_bad(String name) throws Exception { if( !check_file(name) ) new java.io.File(name).delete(); }
  • 10. Java • Resource management - with finally static public boolean check_file2(String name) throws Exception { FileInputStream fs = null; try { fs = new FileInputStream(name); int first = fs.read(); if( first == 32 ) return true; // Lots of code return false; } finally{ if( fs != null ) fs.close(); } }
  • 11. Java • Resource management - with catch static public boolean check_file3(String name) throws Exception { FileInputStream fs = null; try { fs = new FileInputStream(name); int first = fs.read(); if( first == 32 ) return true; // Lots of code } catch(Exception e) {} try { if( fs != null ) fs.close(); } catch(Exception e) {} return false; }
  • 12. C# • Memory management example static public bool check_memory() { Something a = new Something(); a.do_something(); if( a.some_condition() ) return true; // Lots of code return false; }
  • 13. C# • Resource management example static public bool check_file(String name) { using( FileInputStream fs = new FileInputStream(name) ) { int first = fs.read(); if( first == 32 ) return true; // Lots of code } return false; }
  • 14. C++ • System language • Life without garbage collector? • Unique semantic!
  • 15. C++ • Memory management - what C developer thinks? • If I know C I already know C++! static bool check_memory() { ! Something * a = new Something; ! if( !a ) ! ! return false; ! a->do_something(); ! if( a->some_condition() ) ! { ! ! delete a; ! ! return true; ! } ! // Lots of code ! delete a; ! return false; }
  • 16. C++ • Memory management - what C developer thinks? • If I know C I already know C++! static bool check_memory() { ! Something * a = (Something *)malloc( sizeof(Something) ); ! if( !a ) ! ! return false; ! do_something(a); ! if( some_condition(a) ) ! { ! ! free(a); ! ! return true; ! } ! // Lots of code ! free(a); ! return false; }
  • 17. C++ • Are there exceptions in C++? • Are they good or evil? Good! • If I do not use them? • You are allowed not to throw • But good C++ design always uses exceptions, so you better be prepared
  • 18. C++ • Memory management example static bool check_memory() { ! std::auto_ptr<Something> a( new Something ); ! a->do_something(); ! if( a->some_condition() ) ! ! return true; ! // Lots of code ! return false; }
  • 19. C++ • Resource management example static bool check_file(const std::string & name) { ! liba::FileInputStream fs(name); ! int first = fs.read(); ! if( first == 32 ) ! ! return true; ! // Lots of code ! return false; }
  • 20. C++ • Resource management example static bool check_file(const std::string & name) { ! std::auto_ptr<liba::FileInputStream> fs( liba::create_fis(name) ); ! int first = fs->read(); ! if( first == 32 ) ! ! return true; ! // Lots of code ! return false; }
  • 21. C++ • Delete is for implementing libraries! { std::auto_ptr<Something> a( new Something(...) ); if( ... ) return; } • No difference between memory and other resource types
  • 22. Objective-C • Memory management - what C developer thinks? • If I know C I already know Objective-C! -(bool)check_memory { ! Something * a = [[Something alloc] init]; ! if( !a ) ! ! return false; ! [a do_something]; ! if( [a some_condition] ) ! { ! ! [a release]; ! ! return true; ! } ! // Lots of code ! [a release]; ! return false; }
  • 23. Objective-C • Memory management - what C developer thinks? • If I know C I already know Objective-C! static bool check_memory() { ! Something * a = (Something *)malloc( sizeof(Something) ); ! if( !a ) ! ! return false; ! do_something(a); ! if( some_condition(a) ) ! { ! ! free(a); ! ! return true; ! } ! // Lots of code ! free(a); ! return false; }
  • 24. Objective-C • Are there exceptions in Objective-C? • Are they good or evil? Absolutely good! -(void)parse_object:(NSDictionary *)dic { ! // Lots of code ! int val = [[[dic objectForKey:@"users"] objectAtIndex:0] intValue]; ! // Lots of code } -(void)parse_object:(NSDictionary *)dic { ! // Lots of code ! NSArray * arr = [dic objectForKey:@"users"]; ! if( ![arr isKindOfClass:[NSArray class]] ) ! ! return; // But we must tell about error... ! NSNumber * num = [arr objectAtIndex:0]; ! if( ![num isKindOfClass:[NSNumber class]] ) ! ! return; // But we must tell about error... ! int val = [num intValue]; ! // Lots of code }
  • 25. Objective-C • Memory management example -(bool)check_memory { ! Something * a = [[[Something alloc] init] autorelease]; ! [a do_something]; ! if( [a some_condition] ) ! ! return true; ! // Lots of code ! return false; }
  • 26. Objective-C • Memory management example -(bool)check_memory { ! Something * a = [[[Something alloc] init] autorelease]; ! [a do_something]; ! if( [a some_condition] ) ! ! return true; ! // Lots of code ! return false; } • Afraid of autorelease? • Just start using it! • It is widely used in Cocoa
  • 27. Memory and resource management LONG-LIVED OBJECTS
  • 28. Approaches Garbage collector Ownership graph
  • 29. Approaches • It takes lots of CPU time to untangle this!
  • 30. Approaches • You must prove the graph is acyclic!
  • 31. Approaches • What is more scary than memory leak?
  • 32. Approaches • What is more scary than memory leak? • Dangling pointer!
  • 33. Objective-C • Retaining @interface Something : NSObject { ! Anything * a; } @end @implementation Something -(void)do_something { ! Anything * new_a = [[[Anything alloc] init] autorelease]; ! [a release]; // [a autorelease]; ! a = [new_a retain]; } -(void)dealloc { ! [a release]; ! [super dealloc]; } @end
  • 34. Objective-C • Retaining @interface Something : NSObject { ! Anything * a; } @property(nonatomic, retain) Anything * a; @end @implementation Something @synthesize a; -(void)do_something { ! Anything * new_a = [[[Anything alloc] init] autorelease]; ! self.a = new_a; } -(void)dealloc { ! self.a = 0; ! [super dealloc]; } @end
  • 35. Objective-C • Subtle differences ! self.a = new_a; // Call property ! self->a = new_a; // Use variable ! a = new_a; // ???
  • 36. Objective-C • Subtle differences @interface Something : NSObject { ! Anything * a_zlo_hren; } @property(nonatomic, retain) Anything * a; @end @implementation Something @synthesize a = a_zlo_hren; -(void)do_something { ! Anything * new_a = [[[Anything alloc] init] autorelease]; ! self.a = new_a; // Call property ! self->a = new_a; // Use variable ! a = new_a; // ??? }
  • 37. Objective-C • 4 lines to free the memory? Too much. Anything * a_zlo_hren; @property(nonatomic, retain) Anything * a; @synthesize a = a_zlo_hren; ! self.a = 0; // In dealloc
  • 38. Objective-C++ • Objective C is also C++ @interface Something : NSObject { ! NSPtr<Anything> a; } @end @implementation Something -(void)do_something { ! Anything * new_a = [[[Anything alloc] init] autorelease]; ! a = new_a; } @end • 4 lines go down to 1, good!
  • 39. Objective-C++ • Retain cycles @interface Something : NSObject { ! Anything * a; } @property(nonatomic, retain) Anything * a; @end @interface Anything : NSObject { ! Something * s; } @property(nonatomic, retain) Something * s; @end
  • 40. Objective-C++ • Retain cycles @interface Something : NSObject { ! Anything * a; } @property(nonatomic, retain) Anything * a; @end @interface Anything : NSObject { ! Something * s; } @property(nonatomic, retain) Something * s; @end
  • 41. Objective-C++ • Retain cycles @interface Something : NSObject { ! Anything * a; } @property(nonatomic, retain) Anything * a; @end @interface Anything : NSObject { ! Something * s; } @end
  • 42. Retain cycles • Can compiler find them? • Can runtime find them? • Can tools find them? • Is there a simple approach to avoid them?
  • 43. Retain cycles • Can compiler find them? Yes, soon (experimental languages). • Can runtime find them? • Can tools find them? • Is there a simple approach to avoid them?
  • 44. Retain cycles • Can compiler find them? Yes, soon (experimental languages). • Can runtime find them? Yes, Garbage Collector. • Can tools find them? • Is there a simple approach to avoid them?
  • 45. Retain cycles • Can compiler find them? Yes, soon (experimental languages). • Can runtime find them? Yes, Garbage Collector. • Can tools find them? Yes, if included in test cases. • Is there a simple approach to avoid them?
  • 46. Retain cycles • Can compiler find them? Yes, soon (experimental languages). • Can runtime find them? Yes, Garbage Collector. • Can tools find them? Yes, if included in test cases. • Is there a simple approach to avoid them? Yes, analyze architecture.
  • 47. Objective-C • Containers always retain @interface Something : NSObject { ! NSMutableArray * a; } @property(nonatomic, retain) NSMutableArray * a; @end -(void)do_something { ! Anything * new_a = [[[Anything alloc] init] autorelease]; ! Anything * new_a2 = [[[Anything alloc] init] autorelease]; ! [a addObject:new_a]; ! [a addObject:new_a2]; }
  • 48. Objective-C • If we do not want to retain? @interface Something : NSObject { ! NSMutableArray * a; } @property(nonatomic, retain) NSMutableArray * a; @end -(void)do_something { ! Anything * new_a = [[[Anything alloc] init] autorelease]; ! Anything * new_a2 = [[[Anything alloc] init] autorelease]; ! [a addObject:[NSValue valueWithNonretainedObject:new_a]]; ! [a addObject:[NSValue valueWithNonretainedObject:new_a2]]; } -(void)use_something { ! Anything * aa = [[a objectAtIndex:0] nonretainedObjectValue]; }
  • 49. Objective-C • What if we retain by accident? @interface Something : NSObject { ! NSMutableArray * a; } @property(nonatomic, retain) NSMutableArray * a; @end -(void)do_something { ! Anything * new_a = [[[Anything alloc] init] autorelease]; ! Anything * new_a2 = [[[Anything alloc] init] autorelease]; ! [a addObject:new_a]; // Someone forgot ! [a addObject:new_a2]; // Someone forgot }
  • 50. Objective-C • Containers are untyped @interface Something : NSObject { ! NSMutableArray * a; // Of Anything } @property(nonatomic, retain) NSMutableArray * a; // Of Anything @end -(void)do_something { ! Anything * new_a = [[[Anything alloc] init] autorelease]; ! Anything * new_a2 = [[[Anything alloc] init] autorelease]; ! [a addObject:new_a]; ! [a addObject:new_a2]; }
  • 51. Objective-C • Untyped containers are hard to prove @interface Something : NSObject { ! NSMutableArray * a; // Of Anything } @property(nonatomic, retain) NSMutableArray * a; // Of Anything @end -(void)do_something { ! Anything * new_a = [[[Anything alloc] init] autorelease]; ! NSString * str = @"Hi"; ! [a addObject:new_a]; ! [a addObject:str]; }
  • 52. Objective-C++ • We can use great STL containers @interface Something : NSObject { ! std::vector<Anything *> a; } @end -(void)do_something { ! Anything * new_a = [[[Anything alloc] init] autorelease]; ! NSString * str = @"Hi"; ! a.push_back( new_a ); ! a.push_back( str ); }
  • 53. Objective-C++ • Retain strategy is independent @interface Something : NSObject { ! std::vector< NSPtr<Anything> > a; } @end -(void)do_something { ! Anything * new_a = [[[Anything alloc] init] autorelease]; ! NSString * str = @"Hi"; ! a.push_back( new_a ); ! a.push_back( str ); }
  • 54. Objective-C++ • Integration is almost flawless! • Apple teams actually use C++ and STL @interface Something : NSObject { ! std::vector< id<UIActionSheetDelegate> > a; } @end -(void)do_something { ! std::for_each(a.begin(), a.end(), ^(id<UIActionSheetDelegate> x) { ! ! [x actionSheetCancel:nil]; ! }); }
  • 55. Success • alloc-init-autorelease idiom • NSPtr or @property(retain) to manage retain/release • Use text editor to eliminate all retain, release • Architecture with no cycles • Typed containers (STL), so the compiler can actually prove most of your architecture
  • 56. What we forgot? • Active objects (timers, http requests) • Parallel execution (NSOperation)
  • 57. What we forgot? • Active objects (timers, http requests) • Parallel execution (NSOperation) Do not worry! This is also easy!
  • 58. Q&A Q&A Grigory Buteyko hrissan@mail.ru www.dataart.com