programing

Objective C에서 속성 이름 앞에 밑줄 추가

projobs 2021. 1. 14. 08:01
반응형

Objective C에서 속성 이름 앞에 밑줄 추가


나는 이전에 내 변수 이름에 밑줄을 사용하지 않았는데, 아마도 대학 자바 시절의 이월 일 것이다. 그래서 Objective C에서 속성을 정의 할 때 이것이 제가 자연스럽게하는 일입니다.

// In the header
@interface Whatever
{
    NSString *myStringProperty
}

@property (nonatomic, copy) NSString *myStringProperty;

// In the implementation
@synthesize myStringProperty;

그러나 거의 모든 예에서 다음과 같이 수행됩니다.

// In the header
@interface Whatever
{
    NSString *_myStringProperty
}

@property (nonatomic, copy) NSString *myStringProperty;

// In the implementation
@synthesize myStringProperty = _myStringProperty;

밑줄에 대한 혐오감을 극복해야하는 이유는 그것이해야하는 한 가지 방법이기 때문입니다.이 스타일이 선호되는 좋은 이유가 있습니까?

업데이트 : 요즘 자동 속성 합성을 사용하면 @synthesize를 생략 할 수 있으며 결과는 사용했던 것과 동일합니다.

@synthesize myStringProperty = _myStringProperty;

Apple의 선호도를 명확하게 보여줍니다. 나는 걱정을 멈추고 밑줄을 사랑하는 법을 배웠습니다.


나는 항상 밑줄을 사용합니다. 지역 변수와 인스턴스 변수를 명확하게 구분합니다. 또한 다음 상황에서 컴파일러 경고를 방지합니다.

@interface MyClass
{
    NSString *name
}

@property (nonatomic, copy) NSString *name;

- (id) initWithName:(NSString *) name;
@end

@implementation MyClass

@synthesize name;

// The following method will result in a compiler warning
// (parameter name same as ivar name)
- (id) initWithName:(NSString *) name {
   if (self = [super init]) {
      self.name = name;
   }

   return self;
}

@end

편집 :

반대 투표를 견디고 댓글을 읽은 후에 제 요점을 말씀 드리겠습니다.

Apple은 ivar의 속성과 동일한 이름을 사용할 것을 권장합니다. Apple은 또한 속성이 소문자로 시작하도록 권장합니다. 또한 Apple은 지역 변수가 소문자로 시작하도록 권장합니다.

이제 문제가 생겼습니다. 코드를 읽고 사용중인 변수를 볼 때 이름 지정 규칙으로이 변수가 ivar인지 지역 변수인지 알 수 없기 때문입니다. 짜증 난다. 해결책은 ivar 및 지역 변수에 대해 다른 이름 지정 규칙을 사용하는 것입니다. 그것은 평범한 상식입니다.

이 명명 규칙을 구현하는 방법은 관련이 없습니다. 정말로 원한다면 ivar 이름에 "_WOOHAHA"를 추가하면됩니다. 나는 상관하지 않습니다 (하지만 다른 사람들이 그렇게 할 수도 있습니다). 문제는 자신이하고있는 일을 아는 사람들이 ivar에 "밑줄 접두사"를 사용하기로 결정한 것입니다. IMHO, 그들은 자신의 회사가 다른 것을 추천하더라도 올바른 결정을 내 렸습니다. (제가 말하는 개발자는 주요 Apple 프레임 워크와 .NET Framework 클래스를 작성하는 사람들입니다)

결국 코드 품질은 설교하는 사람들이 따르지 않는 어리석은 규칙을 따르는 것보다 더 중요합니다.


여러분이 보여준 코드에 대한 또 다른 언급 : 문자열 속성에 유지사용하지 마십시오 . 대신 복사사용해야 합니다.

속성 복사 / 유지에 대한 자세한 내용은 다음을 참조하세요.

NSString 속성 : 복사 또는 유지?


_ 접두사가 붙은 인스턴스 변수의 명명 규칙은 2012-02-16 개정 이후 Apple이 "Coding Guidelines for Cocoa"에서 그 이유와 함께 명확하게 명시했습니다.

인스턴스 변수의 이름이 저장된 속성을 간결하게 설명하는지 확인하십시오. 일반적으로 인스턴스 변수에 직접 액세스해서는 안됩니다. 대신 접근 자 메서드를 사용해야합니다 (init 및 dealloc 메서드에서 인스턴스 변수에 직접 액세스합니다). 이를 알리기 위해 인스턴스 변수 이름 앞에 밑줄 (_)을 붙입니다. 예를 들면 다음과 같습니다.

@implementation MyClass {
    BOOL _showsTitle;
}

선언 된 속성을 사용하여 인스턴스 변수를 합성하는 경우 @synthesize 문에 인스턴스 변수의 이름을 지정합니다.

@implementation MyClass
@synthesize showsTitle=_showsTitle;

https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/CodingGuidelines/Articles/NamingIvarsAndTypes.html#//apple_ref/doc/uid/20001284-BAJGIIJE

Stanford University의 Paul Hegarty가 가르친 iTunes U, iPhone App Development CS193p Fall 2011 강의에서도이 컨벤션을 설명합니다.

http://itunes.apple.com/itunes-u/ipad-iphone-application-development/id473757255

나는이 질문이 꽤 오래전에 질문되었다는 것을 알고 있지만 나도 같은 질문을했고 나의 발견을 공유하고 싶었다.


Current suggested Objective-C 2.0 practice is to use the same name for the ivar as the property. You can optionally assign a different ivar in the @property declaration, but the fact that by default, synthesized accessors for a property will access the ivar with the same name as the property indicates that's the pattern they expect you to follow.

No matter what, since objects still have to send messages to themselves to access properties, it's hard to confuse when you're accessing a property or when you're accessing its backing ivar directly, though using the 2.0 dot access to properties does make it more possible. Using the standard message passing syntax makes intent more explicit, IMO.

@interface Foo : NSObject {
     NSNumber *bar;
} 
@property(readwrite, retain) NSNumber * bar
@end

@implementation Foo 
@synthesize bar;

-(void) baz {
   NSNumber *numberOne = [NSNumber numberWithInt: 1];   
   //Both set the value of bar through either the your custom or the synthesized setter method
   [self setBar:numberOne];  
   self.bar = numberOne; 

   //Both get the value of bar through your synthesized or your custom accessor method
   NSNumber *fooBar = [self bar];
   fooBar = self.bar;

   //Both manipulate the bar ivar directly
   bar = numberOne;
   fooBar = bar;
}
@end 

Apple reserves selectors beginning with underscore for their own "private" methods and that would include properties. I don't think they reserve _ for ivar names though.

Personally, I would steer clear of using underscore to start any kind of variable name. It's an opaque convention. What if somebody else uses underscore for locals and no underscore for instance variables? What if you accidentally omit the underscore in a method where you have a local defined with the same name?

It's much better to make your local names different from your ivar names. For example in a setter you might use newName or neWValue.


It is purely a style issue.

I don't know which examples use the underscored ivar style. The official Apple examples (e.g. CryptoExercise) do not prefix the ivars with _.


I will just point out that a new navigation project using core data uses trailing underscores by default and makes the variables private.

@interface MyTestAppDelegate : NSObject <UIApplicationDelegate> {

    UIWindow *window;
    UINavigationController *navigationController;

@private
    NSManagedObjectContext *managedObjectContext_;
    NSManagedObjectModel *managedObjectModel_;
    NSPersistentStoreCoordinator *persistentStoreCoordinator_;
}

@interface RootViewController : UITableViewController <NSFetchedResultsControllerDelegate> {

@private
    NSFetchedResultsController *fetchedResultsController_;
    NSManagedObjectContext *managedObjectContext_;
}

The KVC part of the runtime expects either a name or _name ivar when using valueForKey: on an object when it cant find a message to retrieve that variable. see http://developer.apple.com/documentation/Cocoa/Conceptual/KeyValueCoding/Concepts/SearchImplementation.html

If the runtime bothers to search for _name and the apple documentation mentions the _name first there might be a good reason for this. Let's take a look at some SDK classes: UINavigationBar.h this class has underscores in front of all ivars, UIView too... the list goes on. Well maybe it is that way with the new fangled iOS SDK and good ole NS* classes don't do thinges that way... wrong; they use the underscore as well in the header files.

Apple uses the underscore in private API messages as well as ivars. I can't understand why their examples do not push this behavior especially when the runtime bothers to have this so called "naming convention" hard coded into the variable search path. It would be nice to see some consistency.

Just a note, there is a strict naming scheme you have to follow to be KVC compliant; the link above helps you to conform to this to use this handy feature of the runtime.

ReferenceURL : https://stackoverflow.com/questions/3521254/prefixing-property-names-with-an-underscore-in-objective-c

반응형