1

例如,我 subclass UIView,其中myString定义了一个名为的弱属性。@synthesize myString = _myString;语句有错误消息: Semantic Issue: @synthesize of 'weak' property is only allowed in ARC or GC mode

MyUIView.h文件:

@interface MyUIView : UIView

@property (nonatomic, weak) NSString *myString;

@end

MyUIView.m文件:

#import "MyUIView.h"

@implementation MyUIView

@synthesize myString = _myString; // This statement causes an error whose message is Semantic Issue: @synthesize of 'weak' property is only allowed in ARC or GC mode

- (void)dealloc
{
    [_myString release];

    [super dealloc];
}

// Other methods

@end

然后我删除了这个@synthesize myString = _myString;语句还有另一个错误[_myString release];Semantic Issue: Use of undeclared identifier '_text'

如果不需要像myString上面那样合成或释放弱属性,我应该像这样重写代码:

MyUIView.h文件:

@interface MyUIView : UIView

@property (nonatomic, weak) NSString *myString;

@end

MyUIView.m文件:

#import "MyUIView.h"

@implementation MyUIView

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

// Other methods

@end
4

2 回答 2

7

weak is a valid property attribute only when ARC (or GC) is enabled.

You can either switch to ARC (strongly advisable) or use an assign or unsafe_unretained attribute instead, at the cost of losing the benefit of a weak reference (see Whats the difference between 'weak' and 'assign' in delegate property declaration)

That being said, I think both assign and weak won't accomplish anything desirable in the specific case.

Unless you really want to avoid a strong reference to that string, the appropriate property declaration would go as follows:

@property (nonatomic, copy) NSString *myString;

On why copy and not retain (or strong), you can read NSString property: copy or retain?

于 2013-11-02T19:02:00.030 回答
0

NSString(以及任何其他具有可变子类的不可变类)应合成为copy.

@property (copy) NSString *myString;

第一条评论:是的。(非原子,副本)很好。

第二条评论:你不需要,在现代的objective-c语法中也是如此。无论哪种方式都会_myString创建一个 ivar。_myString是的,如果您使用,则需要释放copy

于 2013-11-02T18:15:19.037 回答