Objective-C 2.0中的属性是否需要声明相应的实例变量?例如,我习惯做这样的事情:
MyObject.h
@interface MyObject : NSObject {
NSString *name;
}
@property (nonatomic, retain) NSString *name;
@end
Run Code Online (Sandbox Code Playgroud)
MyObject.m
@implementation
@synthesize name;
@end
Run Code Online (Sandbox Code Playgroud)
但是,如果我这样做了:
MyObject.h
@interface MyObject : NSObject {
}
@property (nonatomic, retain) NSString *name;
@end
Run Code Online (Sandbox Code Playgroud)
这仍然有效吗?它与我之前的例子有什么不同吗?
我倾向于在我的类中专门使用属性,特别是现在您可以在类扩展中声明属性,这要归功于现代的Objective-C 2.0运行时 - 我使用此功能来创建"私有"属性.
我的问题是,是否有任何理由再次在类接口中声明ivars.我更喜欢面向公众的界面尽可能地简洁和干净,只是揭示我班级中相关的方面.
例如,我倾向于做以下事情:
MyClass.h
:
@interface MyClass : NSObject
@property (nonatomic, copy) NSString * publicString;
@property (nonatomic, copy, readonly) NSString * readOnlyString;
@end
Run Code Online (Sandbox Code Playgroud)
MyClass.m
:
@interface MyClass ()
@property (nonatomic, copy, readwrite) NSString * readOnlyString;
@property (nonatomic, copy) NSString * privateString;
@end
@implementation MyClass
@synthesize publicString = publicString_;
@synthesize readOnlyString = readOnlyString_;
@synthesize privateString = privateString_;
- (void)init
{
self = [super init];
if (self != nil)
{
self.publicString = @"Public String";
self.readOnlyString = @"Read-Only String";
self.privateString …
Run Code Online (Sandbox Code Playgroud) 我已经看过代码示例(来自"初学iPhone 4开发"一书),它们都在接口块中声明了ivars,然后声明了相同的属性.像这样:
@interface ViewController : UIViewController {
UITableView *table;
}
@property (nonatomic, retain) IBOutlet UITableView *table;
Run Code Online (Sandbox Code Playgroud)
这个的目的/好处是什么?据我所知,使用现代运行时版本(iPhone和64位OS X应用程序),您只需要声明属性,并且可以省略声明接口块内的ivars.根据similair线程中的这个答案,它将用于调试目的.但除了调试之外还有其他任何好处,你会使用这种方法吗?
干杯,
彼得
iphone properties objective-c instance-variables modern-runtime
我读了很多关于这个主题的帖子,但我无法完全理解一切.好的,很清楚
self.text = @"MyText" will call the accessory method setText (autogenerated)
_text = @"MyText" will still assign the value but will not call the setText
Run Code Online (Sandbox Code Playgroud)
这很清楚.
但是当我们不使用ARC时,这可能很有用,因为setText将负责内存管理.但是当我们使用ARC时会发生什么?有时如果我使用_text一切正常,有时候如果我不使用"self.text"我的应用程序将无法工作.
那么真正的区别是什么?必须有的不仅仅是内存管理.
让我说我有这个
@interface MyClass:NSObject {
NSMutableString *text;
}
@property (nonatomic ) NSMutableString *text;
Run Code Online (Sandbox Code Playgroud)
在这种情况下是不是相同的呼吁
self.text = @"ok"
Run Code Online (Sandbox Code Playgroud)
要么
text = @"ok" ?
Run Code Online (Sandbox Code Playgroud)
有什么不同?