Gen*_*ari 6 properties conventions objective-c ios4 ivars
我知道从iOS 4开始,现在可以根本不声明iVars,并允许编译器在您合成属性时自动为您创建它们.但是,我找不到Apple关于此功能的任何文档.
此外,是否有关于使用iVars和属性的最佳实践或Apple推荐指南的文档?我总是使用这样的属性:
.h文件
@interface myClass {
NSIndexPath *_indexPath
}
@property(nonatomic, retain) NSIndexPath *indexPath
@end
Run Code Online (Sandbox Code Playgroud)
.m文件
@implementation myClass
@synthesize indexPath = _indexPath;
- (void)dealloc {
[_indexPath release];
}
@end
Run Code Online (Sandbox Code Playgroud)
我使用_indexPath而不是indexPath作为我的iVar名称,以确保我indexPath
在需要使用时不会使用self.indexPath
.但是现在iOS支持自动属性,我不需要担心.但是,如果我省略了iVar声明,我应该如何处理在dealloc中释放它?我被教导在dealloc中释放时直接使用iVars,而不是使用属性方法.如果我在设计时没有iVar,我可以直接调用属性方法吗?
我经历了很多不同的处理方式.我目前的方法是在dealloc中使用属性访问.在我不知道的情况下(在我看来)不要做太多的设法,除非在我知道属性有奇怪行为的情况下.
@interface Class
@property (nonatomic, retain) id prop;
@end
@implementation Class
@synthesize prop;
- (void)dealloc;
{
self.prop = nil;
//[prop release], prop=nil; works as well, even without doing an explicit iVar
[super dealloc];
}
@end
Run Code Online (Sandbox Code Playgroud)
小智 5
相反,我做了以下事情:
@interface SomeViewController : UIViewController
@property (nonatomic, copy) NSString *someString;
@end
Run Code Online (Sandbox Code Playgroud)
然后
@implementation SomeViewController
@synthesize someString;
- (void)dealloc
{
[someString release], someString = nil;
self.someString = nil; // Needed?
[super dealloc];
}
@end
Run Code Online (Sandbox Code Playgroud)
注意:在某些时候,Apple将启用默认的合成,这将不再需要@synthesize指令.