Objective-C (iPhone) ivars and memory management

I will subclass NSURLConnection and use MGTwitterEngine as a base to help me get started. This may not be appropriate. However, in my code I noticed that they do not use @propertyeither @synthesizefor their Ivars. They wrapped ivars in access methods that look like this:

- (NSString *)identifier {
  return [[_identifier retain] autorelease];
}

My question is two parts. First, what effect does retainit follow autorelease? It seems to me that he would cancel himself, or, even worse, the leak.

Secondly, if I changed the header file so that:

@property (nonatomic, retain, readonly) NSString* _identifier;

And used @synthesize indentifier = _identifier, would it not do the same as the access method without writing it down?

Perhaps these are just two different ways to do the same. But I wanted me to have the right understanding. Thank.

+3
source share
4 answers

Using @synthesizewill actually only create the setter and getter method. The code that is automatically generated for you is guaranteed to use the correct memory management, so you don’t have to worry.

Using MGTwitterEngines return [[ivar retain] autorelease] is actually the right way. Let's look at two examples.

Suppose a getter is defined as follows:

-(Foo)foo {
    return foo;
}

And then we execute this code:

  • bar = [[bar alloc] init];// bar has a score of 1.
  • foo = bar.foo;// foo har keep score 1 (belongs to the bar).
  • [bar release];// The bar and all its ivars are emulated!
  • [foo doSomething];// , foo.

:

-(Foo)foo {
    return [[foo retain] autorelease];
}
  • bar = [[bar alloc] init];//bar 1
  • foo = bar.foo;//foo 2 ( , 1 ).
  • [bar release];// ivars !
  • [foo doSomething];// , foo .

, , . , , ca , , .

+8

, autorelease, , . a retain, autorelease. , , . a release . , retain, autorelease, : ", ". , , . , , .

, retain autorelease , . . , , - autorelease? , , _identifier . :

- (NSString *)identifier { return _identifier; }

- (void)aMethod {
    NSString *localId = [self identifier]; // localId refers to _identifier which is only retained by self
    [self methodThatChangesIdentifierAndReleasesItsOldValue];  // self releases _identifier
    NSLog(@"%@", localId); // crash, because localId (old value of _identifier) has been released
}

. NSLog , localId . , retain autorelease getter, , localId .

, identifier . , .

+3

Apple . , ( " 1" Apple) , , , . , ivar , .

+1

, , , , . , _identifier, /alloc/etc /, .

Secondly, yes, you usually do not need to write headings unless you are doing something special other than what looks like a common template. Apple has good documentation on properties, I suggest if you are still fuzzy, you look at them.

0
source

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


All Articles