iOS Development

Memory Management

Michael L. Collard, Ph.D.

Department of Computer Science, The University of Akron

3460:489 iOS Development Fall 2014

Memory Management

Stack: Automatic

{
    int n; // automatic allocation sizeof(int) with name n
    
    
    
    
        
    // automatic deallocation for memory with name n
}

Heap: Requires Management

{
    Object* obj = /* ALLOCATION */;
        
        
        
        
    /* DEALLOCATION */
}
// Variable named obj out of scope

Memory Management

Languages

Objective-C

Self Managed

C/C++ Self-Managed Scenario

{
    struct data* p = malloc(sizeof(struct data));
    
    // use *p
    
    free(p);
}


{
    Object* p = new Object; 

    // use *p... 

    delete p;
}

Library

{
    struct srcml_archive* p = srcml_create_archive();
    
    
    // use *p
    
    
    srcml_free_archive(p);
}

Self-Managed Difficulties

More Typical Library Call

// Location A
struct srcml_archive* p = srcml_create_archive();


// great code distance
// Location B
struct srcml_archive* t = p;


// Location C
free(t);  // where t was copied from pointer p at point B

Self-Managed Memory is Difficult

Resource Acquisition is Initialization

class C {
    srcml_archive* p;
public:
    C() : p(0) { p = new srcml_archive(); }
    ~C() { if (p) delete p; }
};
    
// distant part of program
{
    C c;


        
}

Garbage Collection

Resources

Smart Pointers

{
    std::shared_ptr<srcml_archive> p(new srcml_archive);


    // p's destructor called, and the object is automatically deleted
}


{
    std::shared_ptr<srcml_archive> p(new srcml_archive);

    // some time later
    std::shared_ptr<srcml_archive> p2 = p;

        
    // p and p2's memory only deleted once
}

What is going on?

MRR in Objective C

MRR-pertinent Methods

Simple MRR

// subtitle:  a partial and incomplete guide
{
    srcml_archive* archive = [[srcml_archive alloc] init];


    // ...


    [archive release]
}

MRR Shared Pointers

{
    srcml_archive* archive1 = [[srcml_archive alloc] init];
    srcml_archive* archive2 = archive1;
    [archive2 retain];
    //...



    [archive2 release]; // dealloc is not called
    [archive1 release]; // dealloc finally called
}

ARC

ARC Shared Pointers

{
    srcml_archive* archive1 = [[srcml_archive alloc] init];
    srcml_archive* archive2 = archive1;




     // dealloc called automatically
}

GC vs ARC vs MRR