2012-05-02 8 views
0

파일간에 변수에 액세스하는 방법에 대해 혼란 스럽습니다.목표 C : Getter Methods 대 Class.ivarName

예를 들어

:

나는 3 개 개의 파일이 : 애플, 과일, 그리고

@implementation Fruit 
    #import "Fruit.h" 
{ 
    @synthesize name; 

    -(id) init 
    { 
     self = [super init]; 
     if (self) { 
      name = [[NSMutableArray alloc] init]; 
     } 
     return self; 
    } 
    } 
@end 

Apple.h

Fruit.h

@interface Fruit 
{ 
NSString *name; 
} 
@property (nonatomic, retain) NSString *name; 
@end 

Fruit.m

를 먹어
@interface Apple 
#import Fruit.h 
{ 
Fruit *apple; 
} 
@property (nonatomic, retain) Fruit *apple; 
@end 
0 내가 생각하지 않기 때문에 내 Eat.h 실질적으로 비어 //

Apple.m

#import Apple.h 
@implementation Apple 
@synthesize apple; 

apple = [[Fruit alloc] init]; 
apple.name = @"apple"; 
@end 

가 나는

Eat.m

@implementation Eat 
#import Apple.h 
//why is this not working? 
NSLog(@"I am eating %@", apple.name); 

난 그냥이 쓴 필요 처음부터 예제로. 그래서 누락 된 세미콜론과 같은 바보 같은 구문 오류와 내가 놓친 분명한 사실을 무시하십시오. 나는 단지 내가 고심하고있는 것을 비추고있다.

내 혼란은 Apple.m에서 Fruit 's 이름 ivar에 마침표 (.)로 액세스 할 수 있다는 것입니다. 하지만 Eat.m에서는 사과 이름 ivar에. (.)로 액세스 할 수 없습니다. 나는 getter 메소드를 작성해야한다는 것을 알고 있지만, 파일을 가로 질러가는 방식으로 변수에 직접 접근하는 방법이 있습니까? 나는 그것의 아마 나쁜 프로그래밍 기술을 (심지어 할 수있는 경우) 알아,하지만 난 그냥 기능이 동일하지 왜 혼란 스러워요.

답변

0

Apple이 Fruit 유형 인 경우 'name'속성을 상속합니다. 당신의 예제 구현은 애플을 과일의 한 종류로 보여주지는 않지만 당신이 그것을 의미한다고 가정합니다.

변수 'apple'은 Eat.m에서 사용되고 Apple.m에서는 할당되지만 어디에도 내 보내지 않습니다. Eat.m 컴파일은 "변수 'apple'이 (가)"알 수 없음 "으로 실패했습니다.

'이름'의 과일 필드에는 NSMutableArray가 할당되지만 실제로는 문자열입니다. 컴파일러는 이것에 대해 경고 했어야합니다. 과일에 초기 이름을 지정하는 과일 '초기화'루틴이 없습니다.

/* Fruit.h */ 
@interface Fruit : NSObject { NSString *name; }; 
@property (retain) NSString *name; 
- (Fruit *) initWithName: (NSString *) name; 
@end 

/* Fruit.m */ 
/* exercise for the reader */ 

/* Apple.h */ 
# import "Fruit.h" 
@interface Apple : Fruit {}; 
@end 

/* Apple.m */ 
/* exercise for the reader - should be empty */ 

/* main.c - for example */ 
#import "Apple.h" 
int main() { 
Apple apple = [[Apple alloc] initWithName: @"Bruised Gala"]; 
printf ("Apple named: %@", apple.name); 
} 
: 여기

작동 버전입니다