Objective-C chain calls

I am new to Objective-C, so please forgive me if this question seems silly.

First sample:

int main(int argc, const char* argv[])
{
    @autoreleasepool
    {
        MyCoolDelegate* myCoolDelegate = [[MyCoolDelegate alloc] init];
        [[NSApplication sharedApplication] setDelegate: myCoolDelegate];

        return NSApplicationMain(argc, argv);
    }
}

Second sample:

int main(int argc, const char* argv[])
{
    @autoreleasepool
    {
        [[NSApplication sharedApplication] setDelegate: [[MyCoolDelegate alloc] init]];

        return NSApplicationMain(argc, argv);
    }
}

As a C ++ programmer, I expect that both main functions should have the same behavior, but the second main crashes on return NSApplicationMain(argc, argv);, while the first sets the delegate and works as expected.

Could you explain what is the difference between these samples? Is there some kind of black magic around Objective-C temporary objects (I assume I [MyCoolDelegate alloc] init]will return a temporary type object MyCoolDelegate)?

+4
source share
3 answers

, myCoolDelegate , static xib (, Xcode, File > New Project... > Cocoa Application).

. " ", ( !), , myCoolDelegate, , NSApplicationMain.

: " . - , , - ."

-setDelegate: / , , . NSApplication __unsafe_unretained delegate ( ) __weak ( OS X). , NSApplication delegate , , . delegate , -setDelegate:.

: , . , , . , , , , -, , . , . myCoolDelegate " " (ivar, staic ) objc_precise_lifetime .

__attribute__((objc_precise_lifetime)) MyCoolDelegate* myCoolDelegate = [[MyCoolDelegate alloc] init];

, , , , ivar - " ", .

+5

@tenfours, :

MyCoolDelegate *myCoolDelegate = [[MyCoolDelegate alloc] init];

"__strong" , :

__strong MyCoolDelegate *myCoolDelegate = [[MyCoolDelegate alloc] init];

:

__unsafe_unretained MyCoolDelegate *myCoolDelegate = [[MyCoolDelegate alloc] init];

() .

+6

myCoolDelegate , , myCoolDelegate @autoreleasepool, .

myCoolDelegate - . , .

If it setDelegatesaves the object, the object will continue to live with the amount remaining at 1, and your application will not crash when the application tries to use it.

If, on the other hand, it setDelegateretains only a weak link, your application will break because its stop count is 0 after the call setDelegate, so the object is freed before NSApplicationMain.

+4
source

Source: https://habr.com/ru/post/1524154/


All Articles