Chris Grimm
Chris Grimm

Reputation: 771

Questions related to the "strong" property in objective-c

Recently, I have been working with obj-c for iOS development, and have been perplexed by the "strong" property that can be attached to variables in classes.

1) First and foremost, in a practical sense, what exactly does "strong" do?

2) I've noticed when constructing several obj-c classes that "strong" is typically typed in a @property context (ie @property (strong) UIImage *pic1, *pic2;) if one didn't want to declare a variable with the property/synthesize setup, is it possible to give such a variable the "strong" attribute?

Upvotes: 0

Views: 126

Answers (2)

jscs
jscs

Reputation: 64002

A strong reference takes ownership of an object.

When you set a strong property, the passed object is retained by the property owner, e.g. [theViewController setString:aString]; causes theViewController to take ownership of aString. That object will be released when the property is set to something else.

There's a ownership qualifier, __strong, which makes a variable behave the way I've described above. It is the default for any object variable -- NSArray * a; is a strong reference, equivalent to __strong NSArray * a;. The one difference is that the object will be released not just when the variable is re-set, but when it goes out of scope, as at the end of a method:

- (void)activate {
    NSArray * a = [NSArray array];
    // a is __strong by default, takes ownership

} // a is going out of scope. To prevent a leak, ARC releases the array

Upvotes: 2

Senior
Senior

Reputation: 2259

1) Strong is a the ARC replacement for retain. Basically, it means that when assigning a value to this property, such as [foo setBar: someValue], the instance variable that backs the property bar will increment the retain count on the parameter someValue passed to setBar.

2) I think what you are referring to is the use of the __strong prefix, so yes.

Upvotes: 1

Related Questions