问题
I'm adding Swift classes to an old project. It went well, until I tried adding a property to the Swift class. The generated header doesn't compile.
I think the problem is, in the generated code, Swift omitted strong ownership and only declared it as nonatomic. This should normally be enough, because @property should default to strong ownership, right?
So basically these are equivalent:
@property (nonatomic) NSDate *aDate;@property (nonatomic, strong) NSDate *aDate;
But, in my case, it seems like it is defaulting to assign instead of strong, according to the compiler message.
I'm using Xcode 6 GM, and the project has ARC turned on.
Any idea why it is not defaulting to strong? Can I change this somehow?
回答1:
After numerous experiments, I've found out a subtlety that determines the default ownership behavior of a property:
- If a header file is imported only into ARC-enabled classes, and there is no default ownership declared, then the ownership of the property within this header file is
strong. - If a header file is imported into at least one non-ARC class, and there is no default ownership declared, then the ownership of the property is
assign!
This means also, you must not import a -Swift.h header into any non-ARC classes, as it will change the behavior of all the properties and emit warnings (which in my case were converted to errors).
Pretty weird IMHO...
Example:
- we have classes
SourceClass,ARCClass(ARC-enabled) andMRCClass(ARC-disabled) SourceClass.hhas:@property (nonatomic) NSDate *date;
Subtlety:
- If we add
#import "SourceClass.h"only inARCClass.horARCClass.m,- the property
datehas ownershipstrong. - the declaration is equivalent to
@property (nonatomic, strong) NSDate *date;.
- the property
- As soon as we add
#import "SourceClass.h"toMRCClass.horMRCClass.m,- the property
datewill have ownershipassigninstead. - the declaration is changed to
@property (nonatomic, assign) NSDate *date;.
- the property
回答2:
I'm sure that, at one time, "assign" was the default and this...
http://cagt.bu.edu/w/images/b/b6/Objective-C_Programming_Language.pdf
"assign - Specifies that the setter uses simple assignment. This is the default."
...seems to confirm that (page 59).
However, I also see an Apple document ("Programming with Objective-C") that says, "By default, both Objective-C properties and variables maintain strong references to their objects". I believe the change was made with the introduction of ARC.
Although you say ARC is turned on, if this project is old enough it may be that something is still around to interfere with ARC settings.
I realize this isn't a definitive answer but perhaps checking project settings (or cleaning up the project) with this change in mind may help.
来源:https://stackoverflow.com/questions/25917861/why-obj-c-property-default-ownership-assign-instead-of-strong