如何将值设置为自定义对象属性,该属性作为另一个自定义对象的属性

时间:2018-12-13 12:25:09

标签: objective-c

这就是我所拥有的

let controller:WalletView = self.storyboard!.instantiateViewController(withIdentifier: "MyView") as! WalletView
            controller.view.frame = self.view.bounds;
            controller.willMove(toParent: self)
            self.view.addSubview(controller.view)
            self.addChild(controller)
            controller.didMove(toParent: self)

然后我要这样做:

@inerface Face : NSObject    
   @property (nonatomic, assign) long idO;
   @property (nonatomic, assign) NSString *text;
   @property (nonatomic, assign) Eyes *eyes;
@end

@interface Eyes : NSObject
   @property(nonatomic, assign) NSString *color;
   @property(nonatomic, assign) NSNumber *size;
@end

但是我只能得到:“ trying-(null)-(null)”。我该怎么办?

3 个答案:

答案 0 :(得分:3)

您需要保留内容或存档:

https://developer.apple.com/documentation/objectivec/nsobject?language=objc

  @inerface Face : NSObject
  @property (nonatomic, retain) long idO;
  @property (nonatomic, retain) NSString *text;
  @property (nonatomic, retain) Eyes *eyes;
  @end

  @interface Eyes : NSObject
  @property(nonatomic, retain) NSString *color;
  @property(nonatomic, retain) NSNumber *size;
  @end

并在NSObject中添加init方法

  - (id)init

  {

  if (self = [super init]) {

    self.eyes = [[Eyes alloc]init];

    return self;


   } else {

    return nil;
    }
  } 

快乐编码;)

答案 1 :(得分:2)

Face *f  = [[Face alloc] init]; // Face is Initialization 
f.text = @"trying";
f.eyes.color = @"Blue"; // Eyes is not 
f.eyes.size = 0.4f; 

NSLog(@"%@ - %@ - %@ ", f.text, f.eyes.color, f.eyes.size);

(null)-由于对象不是init,两个实例变量的(null)都为null。


尝试

Face *f  = [Face new];
    f.text = @"trying";
    Eyes *eyes = [Eyes new];
    eyes.color = @"Blue";
    eyes.size = @0.4f;
    f.eyes = eyes;
//    f.eyes.color = @"Blue";
//    f.eyes.size = @0.4f;
    NSLog(@"%@ - %@ ", f.text, f.eyes.color)

答案 2 :(得分:1)

您需要保留属性的内容。

@interface Face : NSObject
@property (nonatomic, strong) long idO;
@property (nonatomic, strong) NSString *text;
@property (nonatomic, strong) Eyes *eyes;
@end

@interface Eyes : NSObject
@property(nonatomic, strong) NSString *color;
@property(nonatomic, strong) NSNumber *size;
@end


@implementation Face
@synthesize idO;
@synthesize text;
@synthesize eyes;
@end

@implementation Eyes 
@synthesize color;
@synthesize size;
@end