release/autorelease confusion in cocoa for iphone

前端 未结 6 1586
迷失自我
迷失自我 2020-12-15 01:48

I\'m slowly teaching myself cocoa for the iPhone(through the Stanford Class on iTunes U) and I\'ve just gone through the part on memory management, and I wanted to hopefully

6条回答
  •  孤城傲影
    2020-12-15 02:19

    Does the NSString class call autorelease automatically as part of the assignment?

    The NSString class didn't do anything because you didn't send it a message. All you did was assign to a variable. NSString doesn't find out about this, and it's none of its business.

    Also, is there any difference between the two *temp objects here after these statements? They both contain the same string, but are there memory/usage ways where they differ?

    They're both NSStrings, they both contain the same value, and they're both presumed immutable. That's all you should ever care about.

    Secondly, with properties, I'm assuming that the autorelease is handled automatically. If I have this:

    @property NSString *firstName;
    @property NSString *lastName;
    
    - (void) dealloc
    {
        //HERE!!!!
    
        [super dealloc];
    }
    

    I'm assuming I don't need to add [firstName release] and [lastName release] (at //HERE!!!!), since that's automatically handled by the properties. Is that correct?

    No. NSObject will not release all your property values for you; you still need to release them yourself there.

    Also, don't do self.firstName = nil and self.lastName = nil in dealloc. Those translate into messages (to your accessor methods), and when you do that in dealloc, you're sending messages to a half-deallocked object. That's asking for trouble. The same applies the other way to initializing property values in init: Using your properties/accessors there would be sending messages to a half-inited object.

提交回复
热议问题