Search code examples
objective-cnulldealloc

How to send 'dealloc' message to nil Object in Objective-c?


I know that nil object does not received message. but dealloc is not.

exam code is here.


Book *theLordOfTheRing = [[Book alloc] init];

...

NSLog(@"title: %@", theLordOfTheRing.titleName);

 theLordOfTheRing.titleName = nil;

[theLordOfTheRing setTitleName:[theLordOfTheRing.titleName stringByAppendingString:@" vol.4"]];

NSLog(@"title: %@", theLordOfTheRing.titleName);

[theLordOfTheRing.titleName dealloc]; //Build is fine with this line.

----- console----

title: The Fellowship

title: (null)


stringByAppendingString: message is not worked but dealloc is worked.

why does work 'dealloc' to nil object?


Solution

  • This code will compile and run because you can send messages to objects which are nil. When you send a message to a nil object the app will just continue executing. When you are calling [theLordOfTheRing.titleName dealloc]; dealloc method is not actually being called because titleName is nil. The program is just continue executing.

    When you run [theLordOfTheRing setTitleName:[theLordOfTheRing.titleName stringByAppendingString:@" vol.4"]]; you are getting (null) because you sending stringByAppendingString to an object (titleName) that is already nil and the method is not being executed. [theLordOfTheRing.titleName stringByAppendingString:@" vol.4"]; will "return" nil and and setTitleName method will be called with parameter being nil.

    You should instead of setting titleName to nil set it to @"" blank string this way stringByAppendingString should work because titleName is still alloc and initialized.

    theLordOfTheRing.titleName = @"";
    

    I hope I am able to explain this clearly. Let me know if you have any questions.