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 (Codemotion Rome)
JavaScript in 2016 (Codemotion Rome)JavaScript in 2016 (Codemotion Rome)
JavaScript in 2016 (Codemotion Rome)Eduard Tomàs
 
JavaScript in 2016
JavaScript in 2016JavaScript in 2016
JavaScript in 2016Codemotion
 
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 (Codemotion Rome)
JavaScript in 2016 (Codemotion Rome)JavaScript in 2016 (Codemotion Rome)
JavaScript in 2016 (Codemotion Rome)
 
JavaScript in 2016
JavaScript in 2016JavaScript in 2016
JavaScript in 2016
 
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

The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilV3cube
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 

Kürzlich hochgeladen (20)

The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of Brazil
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 

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