継承を使用せずに#importがどのように機能するかを理解するのを手伝ってください。
そこで、Personという名前のクラスとBodyという名前の別のクラスを作成しました(どちらのクラスもNSObjectから継承されています)。
Bodyクラスには3つのivarがあります(プロパティで設定)
int hands;
int feet;
int legs;
次に、Bodyクラス(* body)のインスタンスをPersonクラスにインポートして作成しました。私の理解では、Bodyクラスから「タイプ」を作成しました。次に、このivarにプロパティが設定されました。
次に、主に、personという名前のPersonクラスからインスタンスを作成しました。Mainはperson.body.feetを認識しますが、その値を直接取得および設定することはできません。それを実行できる唯一の方法は、その値を新しいint変数に渡してから、新しい変数を出力することです。
明らかに私は苦労している初心者ですが、私は本当にこの問題を理解したいです-
#import <Foundation/Foundation.h>
#import "Person.h"
int main (int argc, const char * argv[])
{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
Person *person = [[Person alloc]init];
// this works and NSLog prints out the value is 2
int feet = person.body.feet = 2;
NSLog(@"person.body = %i",feet);
// this does not work - NSLog prints out the value is 0;
[person.body setFeet:2];
NSLog(@"person.body = %i", person.body.feet );
[person release];
[pool drain];
return 0;
}
#import <Foundation/Foundation.h>
#import "Body.h"
@interface Person : NSObject {
Body *body;
}
@property (assign) Body *body;
@end
#import "Person.h"
@implementation Person
@synthesize body;
@end
#import <Foundation/Foundation.h>
@interface Body : NSObject {
int hands;
int feet;
int legs;
}
@property int hands;
@property int feet;
@property int legs;
@end
#import "Body.h"
@implementation Body
@synthesize hands;
@synthesize feet;
@synthesize legs;
@end