开发者

Objective C: use instance class in other class

In my code, in an class I have an ivar

FirstClass *first;

and I can use first within an instance of this class.

But if I want to access first from another 开发者_开发问答object instance (or even another class), how can I do that?


I assume you're talking about using FirstClass in another source file than its own, right?

In this case you'd have to import its header by adding this to the top of your second class' ".m"-file:

#import "FirstClass.h"

If you also need to reference in your second class' header ".h"-file, then you can add a

@class FirstClass;

before the @interface block. This will tell the compiler that it should consider a class of that name to be existant, but to not bother you with warnings unless you forget to import the given first class' ".h" file in the second class' ".m" file.

To allow access from foreign objects to your SecondClass' firstClass iVar you'll need to implement a getter method for firstClass.

This is done with

@property (nonatomic, readwrite, retain) FirstClass *firstClass;

in the @interface block, and

@synthesize firstClass;

in the @implementation block.

With this set up you can then either call [secondClassInstance firstClass]; or access it via the dot syntax secondClassInstance.firstClass;. My sample will also synthesize a setter method called setFirstClass:. To make the property read-only, change readwrite to readonly in the @property declaration.

Sample:

FirstClass.h:

#import <Cocoa/Cocoa.h>

@interface FirstClass : NSObject {
@private

}

//method declarations

@end

FirstClass.m:

#import "FirstClass.h"

@implementation FirstClass

//method implementations

@end

SecondClass.h:

#import <Cocoa/Cocoa.h>

@class FirstClass;

@interface SecondClass : NSObject {
@private
    FirstClass *firstClass;
}

@property (nonatomic, readwrite, retain) FirstClass *firstClass;

//method declarations

@end

SecondClass.m:

#import "SecondClass.h"

#import "FirstClass.h"

@implementation SecondClass

@synthesize firstClass;

- (id)init {
    if ((self = [super init]) != nil) {
        firstClass = [FirstClass alloc] init];
    }
    return self;
}

- (void)dealloc {
    [firstClass release];
    [super dealloc];
}

//method implementations

@end


I would use a property. Probably in your header of your second class something like

@property (nonatomic, retain) FirstClass *first;

and in your implementation

@synthesize first;

Than when you create an object of your SecondClass

SecondClass *second = [[SecondClass alloc] init];

you can use

second.first
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜