2016-06-17 2 views
1

부모 클래스가 있습니다.하위 클래스 함수에서 부모 클래스 인스턴스 변수에 액세스

헤더 파일 (Parent.h) :

@interface Parent 
@end 

구현 파일 (Parent.m) : 다음

@interface Parent { 
    // I defined a instance vaiable 'name' 
    NSString *name; 
    // another custom type instance variable 
    School *mySchool; 
} 
@end 

@implementation Parent 
... 
@end 

, 나는 Parent을 상속 Child 클래스가 있습니다.

헤더 (Child.h) :

@interface Child : Parent 
-(void)doSomething; 
@end 

구현 파일 (Child.m) :

@implementation Child 
-(void)doSomething{ 
// Here, how can I access the instance variable 'name' defined in Parent class? 
// I mean how to use the 'name' instance, not only get its value. 
// for example: call writeToFile:atomically:encoding:error: on 'name' here 


    // tried to access mySchool defined in parent class 
    // Property 'mySchool' not found on object of type 'Parent' 
    School *school = [self valueForKey:@"mySchool"]; 
} 
@end 

어떻게 자식 클래스 함수에서 상위 클래스에 정의 된 인스턴스 변수를 액세스 할 수 있습니까?

==== 대한 설명 ===

나는 '이름'인스턴스를 사용하는 방법을 의미, 그 값을 구할 수있을뿐만 아니고. 예 : : '이름'에 writeToFile:atomically:encoding:error:을 호출하십시오.

+0

속성을 추가하려면'Parent + Private.h' 파일을 사용할 수 있습니다. 왜냐하면 y 다른 객체가'Parent' 객체의'name'에 접근하는 것을 원하지 않습니다. – Larme

+0

왜 Parent.h에 변수를 정의하지 않습니까? 그러면'self-> name'을 사용하여 액세스 할 수 있습니다. – KudoCC

+0

h 파일에 선언 된 경우 하위 클래스의 self.name을 사용하여 직접 액세스 할 수 있습니다. –

답변

1

키 - 값 코딩을 사용합니다.

설정 :

[self setValue:@"Hello" forKey:@"name"]; 

읽기 :

NSString* name = [self valueForKey:@"name"]; 
[name writeToFile:@"Filename" 
     atomically:YES 
     encoding:NSUTF8StringEncoding 
      error:nil]; 
+0

setter/getter 메소드가 필요하지 않습니까? – Droppy

+0

그렇지 않은 것 같습니다. 방금 해봤 어. 나를 위해 일한다 –

+0

그래, [docs] (https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/KeyValueCoding/Articles/BasicPrinciples.html); 접근 자 * 또는 * 인스턴스 변수가 필요합니다. – Droppy

0

그것은 당신이 정말로 - 정말로 필요로하는 경우, 당신은 수있는 코드에서 사용자 인스턴스 변수에 현재 추천과 공공 헤더에 인스턴스 변수를 선언하지만, 아니에요 이 이전 스타일의 코드를 사용하십시오 :

//Parent.h 
@interface Parent: NSObject { 

@protected 
    NSString *_name; 
    School *_mySchool; 
} 
@end 

//Parent.m 
@implementation Parent 
... 
@end 

//Child.h 
@interface Child : Parent 
-(void)doSomething; 
@end 

//Child.m 
@implementation Child 
-(void)doSomething{ 
    School *school = self->_mySchool; 
    NSString *name = self->_name; 
} 
@end 
+0

에서는 @protected를 생략 할 수 있습니다. 기본 액세스 수준입니다. –

관련 문제