release/autorelease confusion in cocoa for iphone

前端 未结 6 1595
迷失自我
迷失自我 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:14

    About firstName/lastName.

    You should always, for clarity, remember to specify the properties' attributes. The setter default attribute is assign, in this case you want to use retain.

    @interface Person : NSObject
    {
        NSString *firstName;
    }
    @property (retain) NSString *firstName;
    @end
    

    With retain each and only time you use the dot notation to assign a value the compiler inserts a retain: just remember to always use it. For consistency I advice you to write your initializer this way:

    - (id) initWithFirstName:(NSString*) aString
    {
        self.firstName = aString; 
    }
    

    and the dealloc method this way:

    - (void) dealloc
    {
         self.firstName = nil;
    }
    

    About @""-type objects. They are constant NSStrings objects. Just use them as the were (they are) NSString objects and never release them. The compiler takes care of them.

提交回复
热议问题