@property Save - iPhone

I am new to programming on the iPhone. I have the following doubts that prevent me from moving forward. Please consider the following code:

---------.h------
@interface myClass: UIViewController
{
    UIImage *temp;
}

@property (nonatomic, retain) UIImage *temp;

 ---------.m------
 @interface myClass
 @synthesize temp;

 -(void) dealloc
 {
   [temp release];
   [super dealloc];
 } 
  • The above program code. Here it is ... nothing more. I need to declare [temp release] in the dealloc method, although I do not use the property access method in my program at all. What if I do not declare [temp release] in dealloc. Will this create a memory leak, as I release something that I have not saved, since I do not name the method for accessing properties.

  • Also, when I print the save counter for temp, why does it show 0, even if it is stored in @property.

Thanks in advance

+3
source share
3 answers

, , . "dealloc" Apple:

, , ( Cocoa) - , , , , self.temp = nil; dealloc ( apple doc i, ). , , , / dealloc.

0
  • () myClass.temp, . dealloc.

  • @property - , myClass . , .

    myClass *instance = [[myClass alloc] init];
    
    // instance will now retain the value passed in
    // and is therefore responsible for releasing it
    instance.temp = [UIImage imageNamed:@"whatever"];
    
    // if instance is not retained anywhere else,
    // its dealloc will be called
    [instance release];
    

, , MyClass. , .

self.temp = nil; dealloc. , . ...

+1

.

, , @interface, -dealloc. , , , @property.

temp , ObjC temp , .

a -release nil , [ temp release] . -op. temp non-nil -dealloc,, [temp release] .

, temp non-nil , -init , . -init, , , .

: -init. , , temp ivar , -initWithImage:

:

@implementation MyClass

...

- (id) init {
   self = [super init];
   if (self != nil) {
      // The minimal default initializer.
      // temp will already have a value of nil, so you don't need necessarily 
      // need to do anything more, unless temp needs a real value on initialization.
   }
   return self;
}

- (void) dealloc {
...
}

@end


, , - :

@implementation MyClass

...

- (id) initWithImage:(UIImage *)newImage {
   self = [super init];
   if (self != nil) {
      temp = [newImage retain];
   }
   return self;
}

// Implement the default initializer using your more detailed initializer.

- (id) init {
   // In this default initializer, every new instance comes with a temp image!
   return [self initWithImage:[UIImage imageNamed:@"foobar"]];
}

- (void) dealloc {
...
}
@end

-initWithImage: . , -init, -initWithImage:.

, . , -init . . . ( ) .

, . , -init -dealloc, - .

dealloc . , . .

ivars. . , . .

JeremyP Link to Cocoa Conceptual object documentation is good. You should definitely read the "Objects" sections and periodically re-read them, as you gain more experience, write your own custom classes. In the end, all of this will start to make sense.

0
source

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


All Articles