0

I am quite confused on how to access variables across files.

For example:

I have 3 files: Apple, Fruit, and Eat

Fruit.h

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

Fruit.m

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

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

Apple.h

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

Apple.m

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

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

//my Eat.h is practically empty because I don't think I need it

Eat.m

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

I wrote these just as examples from scratch. So ignore silly syntax errors such as missing semi-colons, and obvious things I missed. I'm just mirroring something I am struggling with.

I guess my confusion is that in Apple.m, you can access the Fruit's name ivar with the period symbol (.). But in Eat.m, I cannot access apple's name ivar with a (.). I know I should/could write a getter method, but is there a way to directly access variables in the way I am trying to across files? I know its probably bad programming technique (if it can even be done), but I am just confused why the functionality isn't the same.

1 Answers1

0

If Apple is a type of Fruit then it will inherit the 'name' property. Your example implementation does not show Apple as a type of Fruit but I assume you meant it to be (and more on that later).

The variable 'apple' is used in Eat.m, is assigned in Apple.m but is not exported anywhere. The compilation of Eat.m should have failed with "variable 'apple' is unknown".

The Fruit field of 'name' is assigned a NSMutableArray but it is actually a string. The compiler should have warned about this. And, you don't have a Fruit 'init' routine that assigns an initial name to a fruit.

Here is a version that works:

/* 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);
}
GoZoner
  • 67,920
  • 20
  • 95
  • 145