2010-06-27 2 views
1

필자는 여러 가지 유형의 객체를 저장하는 nsmutablearray를 가지고 있습니다. 이 모든 객체에는 id, type 등 두 개의 비슷한 속성이 있습니다.nsmutablearray에있는 객체의 속성에 액세스하기 iphone sdk

내가하고있는 일은 하나의 요소 배열에있는 현재 작업 객체를 가져 와서 다른 클래스에서 입력 한 속성 ID에 액세스하는 것입니다. 이 클래스는 어떤 객체 유형이 현재 객체인지를 알지 못합니다. 이 객체에 어떻게 접근해야합니까?

나는 일을 시도 :

commentId = [[appDelegate.currentDeailedObject valueForKey:@"id"] intValue]; 
commentType = [appDelegate.currentDeailedObject valueForKey:@"type"]; 

을하지만 그것은 작동하지 않았다.

는이 같은 유형 ID의 객체 생성 :

id *anObject = [appDelegate.currentDeailedObject objectAtIndex:0]; 
commentId = [[anObject valueForKey:@"id"] intValue]; 
commentType = [anObject valueForKey:@"type"]; 

을하지만이 경고 나에게 보여줍니다 잘못된 수신기 종류 ' 1.warning :

2.warning 호환되지 않는 포인터 유형에서 초기화 id * '

어떻게해야합니까?

고지.

답변

0

일반 id 변수는 이미 포인터이므로 포인터 할당을 일반적으로 사용하지 않습니다. 당신은 commentIdcommentType, 예를 들어,에 대한 캐스트를 사용할 수 있습니다

id anObject = [appDelegate.currentDeailedObject objectAtIndex:0]; 

: 그래서 당신은 같은 것을 사용한다 (NSNumber *), 당신의 코드 등

+0

고맙습니다 알렉스는 .. 저도 같은했고, 그것은 단지 자세한 답변을 .. – neha

1

정정 : "*"실종 "ID"후

id anObject = [appDelegate.currentDeailedObject objectAtIndex:0]; 
int commentId = [anObject id]; 
NSString *commentType = [anObject type]; 

공지 사항 및 누락 "valueForKey"(ID가 이미 참조를 나타냅니다) (이있는 NSDictionary 내부의 방법이다 제공된 키로 표시된 값을 리턴합니다).

일반적으로이 코드는 작동해야합니다.
하지만 필요한 두 가지 방법 (예 : "id"및 "type")을 가진 수퍼 클래스 또는 프로토콜을 만드는 것이 좋습니다.

예를 들어 (슈퍼 클래스) :

@interface MyComment : NSObject 
{ 
    NSInteger commentId; 
    NSString *_commentType; 
} 

@property (nonatomic) NSInteger commentId; 
@property (nonatomic, copy) NSString *commentType; 

@end 

@implementation MyComment 

@synthesize commentId, commentType = _commentType; 

- (void)dealloc { 
    [_commentType release]; 

    [super dealloc]; 
} 

@end 

// sample use 
@interface MyCommentNumberOne : MyComment 
{ 
} 
@end 

또 다른 예 (프로토콜) :

@protocol CommentPropertiesProtocol 
@required 
- (NSInteger)commentId; 
- (NSString *)commentType; 
@end 

// sample use 
@interface MyCommentNumberOne : NSObject <CommentPropertiesProtocol> 
{ 
    NSInteger commentId; 
    NSString *_commentType; 
} 
@end 

@implementation MyCommentNumberOne 

- (NSInteger)commentId { 
    return commentId; 
} 
- (NSString *)commentType { 
    return _commentType; 
} 

- (void)dealloc { 
    [_commentType release]; 

    [super dealloc]; 
} 

@end 
+0

고맙습니다을했다. 첫 번째 방법으로 해결되었습니다. – neha

관련 문제