Highlighting instance variables?

Can someone tell me if I / I need to assign / release an instance of the NSString "planetName" instance (as in the example below) or is this done when the class instance is created / allocated?

I understand that int and float do not have to be, but are not sure about NSString and NSArray ...

@interface PlanetClass : NSObject {
        NSString *planetName;
}
- (NSString *)planetName;
- (void)setPlanetName:(NSString *)value;
@end

Like this...

- (id) init {
        [super init];
        planetName = [[NSString alloc] init];
return self;
}

- (void) dealloc {
        [planetName release];
        [super dealloc];
}

** ---------------------------------- ** EDIT: EDIT: Here is another version ** - -------------------------------- **

int main(int argc, const char *argv[]) {

        // ** Allocated here
        PlanetClass *newPlanet_01 = [[PlanetClass alloc] init];
        NSString *newPlanetName = [NSString alloc] init];

        // ** Set the instance variable pointer here
        newPlanetName = @"Jupiter";
        [newPlanet_01 setPlanetName:newPlanetName];

        // ** Released here
        [newPlanet_01 release];
        return 0;
}

init and dealloc methods would be like this ...

- (id) init {
        [super init];
        return self;
}

- (void) dealloc {
        // Always release the current copy of planetName 
        // pointed to by the class instance.
        [planetName release]
        [super dealloc];
}

The setPlanetName method will look like this:

- (void)setPlanetName:(NSString *)newPlanetName {
        if (planetName != newPlanetName) {
               [planetName release];
               planetName = [newPlanetName copy];
        }
}

PS: I do not use properties or synthesize, I have not received this yet.

cheers -gary -

+3
source share
4 answers

.

newPlanetName, . PlanetClass setPlanetName:, PlanetClass , . setPlanetName:, , .

dealloc . , PlanetClass . , , stringWithString:, , PlanetClass, .

, dealloc [newPlanetName release] , .

[newPlanet_01 setPlanetName:@"Jupiter"] newPlanetName .

+1

, , , planetName . Objective-C , - . -setPlanetName:, _ nil ( nil), , -dealloc [planetName release], .

, -copy NSString -retain . , -setPlanetName: :

- (void)setPlanetName:(NSString *)newPlanetName {
  NSString *tempPlanetName = [newPlanetName copy];
  [planetName release];
  planetName = tempPlanetName;
}
+3

planetName - , , int float, .

, int float, planetName .

, planetName nil ( ). planetName , dealloc.

, :

planetName = [[NSString alloc] init];

.

In your setPlanetName method, you will need to free an existing line that planetName points to, assign planetName to a new line, and then save the new line.

Your dealloc method is correct.

+1
source

Your code looks good. Subclasses NSObject( NSStringincluded) must have their own memory controlled by the object that owns it. In this case, this owner PlanetClass.

0
source

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


All Articles