我对如何“设置”和“获取”另一个包含的对象的实例变量感到有些困惑。从下面的代码中可以看出,我首先创建一个包含SolidRocketMotor对象的RocketBody。我在RocketBody init中创建SolidRocketMotor并在RocketBody dealloc中释放它。
我的问题是如何在main(例如设置engCase)中设置/获取引擎(SolidRocketMotor)实例变量?
int main (int argc, const char * argv[]) {
RocketBody *ares_1x;
ares_1x = [[RocketBody alloc] init];
[ares_1x setFuel: [NSNumber numberWithInt:50000]];
[ares_1x setWeight:[NSNumber numberWithFloat:1.8]];
// How to set engCase to "Standard" here?
...
@interface SolidRocketMotor : NSObject
{
NSString *engCase;
NSString *engPropellant;
NSNumber *engIgniter;
NSString *engNozzle;
}
@property(copy) NSString *engCase;
@property(copy) NSString *engPropellant;
@property(copy) NSNumber *engIgniter;
@property(copy) NSString *engNozzle;
@end
@interface RocketBody : NSObject
{
NSNumber *fuel;
NSNumber *weight;
BOOL holdDownBolt_01;
BOOL holdDownBolt_02;
BOOL holdDownBolt_03;
BOOL holdDownBolt_04;
SolidRocketMotor *engine;
}
@property(copy) NSNumber *fuel;
@property(copy) NSNumber *weight;
@property BOOL holdDownBolt_01;
@property BOOL holdDownBolt_02;
@property BOOL holdDownBolt_03;
@property BOOL holdDownBolt_04;
@end
// ------------------------------------------------------------------- **
// IMPLEMENTATION
// ------------------------------------------------------------------- **
@implementation SolidRocketMotor
- (id) init {
self = [super init];
if (self) NSLog(@"_init: %@", NSStringFromClass([self class]));
return self;
}
@synthesize engCase;
@synthesize engPropellant;
@synthesize engIgniter;
@synthesize engNozzle;
- (void) dealloc {
NSLog(@"_deal: %@", NSStringFromClass([self class]));
[super dealloc];
}
@end
// ------------------------------------------------------------------- **
@implementation RocketBody
- (id) init {
self = [super init];
if (self) {
engine = [[SolidRocketMotor alloc] init];
NSLog(@"_init: %@", NSStringFromClass([self class]));
}
return self;
}
@synthesize fuel;
@synthesize weight;
@synthesize holdDownBolt_01;
@synthesize holdDownBolt_02;
@synthesize holdDownBolt_03;
@synthesize holdDownBolt_04;
- (void) dealloc {
NSLog(@"_deal: %@", NSStringFromClass([self class]));
[engine release], engine = nil;
[super dealloc];
}
@end
非常感谢
加里
答案 0 :(得分:2)
假设您有类似的东西并且您声明了SolidRocketMotor *引擎的属性设置:
RocketBody *rb = [[RocketBody alloc] init];
然后你会这样做:
SolidRocketMotor *srm = [[SolidRocketMotor alloc] init];
rb.engine = srm;
和
rb.engine.engCase = whatever;
答案 1 :(得分:1)
您需要在engine
课程中为RocketBody
提供一个访问者。像这样:
@interface RocketBody : NSObject
{
// ...
SolidRocketMotor *engine;
}
// ...
@property(retain) SolidRocketMotor *engine;
@end
@implementation RocketBody
// ...
@synthesize engine;
// ...
@end
有了这个,外部代码可以访问engine
属性:
// Obj-C 2.0 Property style:
ares_1x.engine.engCase = @"Standard";
// or setter/getter method style:
[[ares_1x engine] setEngCase:@"Standard"];