Table of Content

static

Static variable in class method is stored statically and can be initialized only once even if you call the method multiple times.

- (IBAction)clickAction:(id)sender {
    
    static id sharedInstance = nil;
    static dispatch_once_t onceToken;
    
    dispatch_once(&onceToken, ^{
        
        sharedInstance = [[NSObject alloc] init];
    });
    NSLog(@"%@", sharedInstance);
}

And if you set a breakpoint on the static xxxxx lines, you will find it doesn't work, because it was initialized when you compile.

assign

Stack is used for static memory allocation and Heap for dynamic memory allocation, both stored in the computer's RAM.

The assign in ARC is same to the unsafe_unretained in MRC. It seems that __unsafe_unretained and __weak qualifier work the same.

As we know, __unsafe_unretained mean we must be sure that the assigned object exists during the lifetime of the variable. If it fails, the application will crash.

Value types are stored on the stack, it's not a pointer to a Heap address, but a value in memory directly.

So NSlnteger, BOOL, CGFloat types need to be specified assign keyword.

copy

A copy mean that you want to guarantee the state of the object. The copy would invoke the copyWithZone: method.

When a mutable object was sent a copyWithZone: message, it will return a clone immutable object, which retainCount is 1. As to an immutable object, it won't copy ,just return the object itself, but the retainCount +1.

Have a look at the follow code:

NSMutableArray *arr1 = [[NSMutableArray alloc] init];
NSArray *array = @[@1, @2, @3, @4];

[arr1 addObjectsFromArray:array];

NSArray *arr2 = arr1;
NSArray *arr3 = [arr1 copy];

[arr1 removeAllObjects];

NSLog(@"Arr2: %@\nArr3: %@", arr2, arr3);

What do you think of the result?

Arr2: (
)
Arr3: (
    1,
    2,
    3,
    4
)

block

Why we should specify copy as the property attribute? Because block was a stack object, what's more, the only stack object in Objective-C.

A stack object is just an object where the memory for that object is allocated on the stack. It is more faster and more simpler than Heap object, all of the bookkeeping is done by the compiler when you build your program, and never cause memory leak because it always gets destroyed at the end of the scope where it was declared.

While we specify a copy keywords, a block object(actually it is a struct), will be copied to the Heap, it will gain reference-counting as all objects in Cocoa.