0

我对如何跨文件访问变量感到很困惑。

例如:

我有 3 个文件:Apple、Fruit 和 Eat

水果.h

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

水果.m

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

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

苹果.h

@interface Apple
#import Fruit.h
{
Fruit *apple;
}
@property (nonatomic, retain) Fruit *apple;
@end

苹果.m

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

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

//我的 Eat.h 实际上是空的,因为我认为我不需要它

吃.m

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

我从头开始写这些只是作为示例。因此,请忽略愚蠢的语法错误,例如缺少分号,以及我错过的明显内容。我只是在反映我正在努力解决的问题。

我想我的困惑是在 Apple.m 中,您可以使用句点符号 (.) 访问 Fruit 的名称 ivar。但在 Eat.m 中,我无法使用 (.) 访问苹果的名称 ivar。我知道我应该/可以编写一个 getter 方法,但是有没有办法以我尝试跨文件的方式直接访问变量?我知道它可能是糟糕的编程技术(如果它甚至可以完成的话),但我只是很困惑为什么功能不一样。

4

1 回答 1

0

如果 Apple 是一种水果,那么它将继承“名称”属性。您的示例实现并未将 Apple 显示为一种水果,但我认为您的意思是(稍后会详细介绍)。

变量“apple”在 Eat.m 中使用,在 Apple.m 中分配,但不会在任何地方导出。Eat.m 的编译应该因“变量‘苹果’未知”而失败。

'name' 的 Fruit 字段被分配了一个 NSMutableArray 但它实际上是一个字符串。编译器应该对此提出警告。而且,您没有为水果分配初始名称的 Fruit 'init' 例程。

这是一个有效的版本:

/* 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);
}
于 2012-05-03T14:52:53.637 回答