2011-12-23 3 views
0

나는 같은 슈퍼 클래스로부터 상속 받아야하는 다른 객체 들인 NSArray의 인스턴스 변수를 가진 클래스를 가지고 있습니다. 내 질문은 배열의 내용에 특정 클래스의 하위 클래스 인 객체 만 포함되도록 보장하면서 다른 클래스 (해당 컨트롤러)에서 인스턴스 변수 및 메서드에 액세스하려면 어떻게해야합니까? 나는 최소한의 프로토콜을 구현하고 배열의 객체를 id(id *)으로 다시 시도했지만 배열의 모든 인스턴스 변수 나 메소드에 액세스 할 수는 없습니다. 제어기 파일서브 클래스 인스턴스에 접근하기

subclassofClassObject* object; 

에서는 오브젝트 파일

NSArray* components; // contains subclasses of component 

에서 는 거기 subclassOf 기능 매크로의 typedef ... 등 또는 대안 그래서 서브 클래스의 구성 요소의 서브 클래스를 참조 할 컨트롤러의 서브 클래스의 객체. 즉 subclassofClass를 대체 할 항목입니다.

+1

'id *'유형의 변수가 필요합니까? 그것은 이미'Cocoa '객체에 대한 포인터 인'id'에 대한 포인터 일 것입니다. – Monolo

답변

0

나는 확실히 당신이 요구하는지 무엇을 따르지 않는,하지만 어쩌면 다음이 도움이 될 것입니다

당신은 당신이 클래스의 인스턴스가 있는지 확인하거나 isKindOfClass:를 사용하여 서브 클래스 중 하나 있습니다. 내가 먼저 아키텍처 설계에 생각하는 게 좋을 것

id elem = [components objectAtIndex:ix]; 
if ([elem isKindOfClass:[MyBaseClass class]]) 
{ 
    // elem is an instance of MyBaseClass or one of its subclasses so cast is safe 
    MyBaseClass *mbc = (MyBaseClass *)elem; 
    // now can access methods, properties and public instance variables 
    // of MyBaseClass via mbc without warnings 
    ... 
} 
+0

규칙을 고수하고 클래스 이름을 대문자 (및 소문자로 된 메소드 이름)로 시작하십시오 :-) – DarkDust

+0

아 ... 캐스팅. 나는 그것을 잊었다. 감사합니다. – Nicholas

2

: 클래스 MyBaseClass을 주어 예를 들어, 다음 캐스트를 사용합니다. 서브 클래스 구현 내에서 논리를 이동하려고 할 수 있습니다.

@interface BaseClass: NSObject { 
} 
... 
- (void) doMySuperImportantStuff: (id)data; 
@end 

@implementation BaseClass 
... 
- (void) doMySuperImportantStuff: (id)data 
{ 
    // basic implementation here, or common actions for all subclasses 
    NSLog(@"BaseClass is here"); 
} 
@end 


@interface ClassA: BaseClass 
{ 
NSInteger i; 
} 
... 
@end 

@implementation ClassA 
... 
- (void) doMySuperImportantStuff: (id)data 
{ 
    // some specific stuff 
    NSLog(@"ClassA is here, i=%d", i); 
} 
@end 


@interface ClassB: BaseClass 
{ 
    NSString *myString; 
} 
... 
@end 

@implementation ClassB 
... 
- (void) doMySuperImportantStuff: (id)data 
{ 
    // another specific stuff 
    NSLog(@"ClassB is here, myString = %@", myString); 
} 
@end 

// client code example 
.... 
NSArray *list = ...; // list of instances of the subclasses from BaseClass 
for(BaseClass *item in list) { 
    [item doMySuperImportantStuff: userData]; 
} 
관련 문제