최근에 iPhone 앱을 개발하기 시작했습니다. C#에서 오는 Objective-C에는 나를위한 트랩이 있습니다. 다음 스 니펫에서 어떤 일이 일어 났는지 이해하지 못합니다.속성에 대한 액세스 개념 이해 문제
@interface RootViewController : UITableViewController {
NSString *simpleProperty;
NSString *propertyWithUnderscoreIvar;
}
@property (nonatomic, retain) NSString *simpleProperty;
@property (nonatomic, retain) NSString *propertyWithUnderscoreIvar;
@end
@implementation RootViewController
@synthesize simpleProperty;
@synthesize propertyWithUnderscoreIvar = _propertyWithUnderscoreIvar;
- (NSString *)simpleProperty {
return @"Simple property value";
}
- (NSString *)propertyWithUnderscoreIvar {
return @"Property with underscore value";
}
- (void)viewDidLoad
{
[super viewDidLoad];
NSLog([NSString stringWithFormat:@"%i %@", 1, simpleProperty]);
// --> 1 (null)
NSLog([NSString stringWithFormat:@"%i %@", 2, propertyWithUnderscoreIvar]);
// --> 2 (null)
NSLog([NSString stringWithFormat:@"%i %@", 3, _propertyWithUnderscoreIvar]);
// --> 3 (null)
NSLog([NSString stringWithFormat:@"%i %@", 4, self.simpleProperty]);
// --> 4 Simple property value
NSLog([NSString stringWithFormat:@"%i %@", 5, self.propertyWithUnderscoreIvar]);
// --> 5 Property with underscore value
}
왜 처음 세 출력이 null입니까? 속성에 대한 내 자신의 구현이 올바르지 않습니까?
@Sandro - 귀하가 그 의견을 말하면서 편집하고있었습니다. 당신이 ivars를 선언하는 위치에 대한 확장 된 답변을 참조하십시오. – Perception
감사합니다. 나는 스 니펫을 약간 썼다. 이제 인스턴스 변수에 밑줄 접두사를 사용하지 않습니까? – Sandro
ivar과 속성을 구별하는 데 도움이되는 코드 작성 방법으로 (실제로 속성을 사용하려고했을 때 실수로 ivar을 사용하는 것과) 동일한 문제를 피할 수 있습니다. – Perception