如何在Xcode / Obj C中的另一个自定义对象内访问对象的属性?

时间:2013-02-07 17:55:59

标签: object properties null setter getter

正如我新手一样,我有点理解如何使用点表示法创建和访问对象的属性。例如,我有一个带有属性courseName的对象golfCourse,所以golfCourse.courseName = @“我的课程”工作正常。我的问题是,如果我创建一个包含Par和Distance的“holeObject”并在我的课程对象中创建Hole1,Hole2等试图通过golfCourse访问它们.Hole1.Par返回null ...我的各种搜索没有找到任何清晰度..有人能指出我正确的方向吗?

非常感谢

HoleObject.h

#import <Foundation/Foundation.h>

@interface HoleObject : NSObject

@property(nonatomic,strong) NSString* par;
@property(nonatomic,weak) NSString* yellowDistance;
@end

HoleObject.m
#import "HoleObject.h"

@implementation HoleObject

@synthesize
par=_par,
yellowDistance=_yellowDistance,


-(void) encodeWithCoder:(NSCoder*)encoder
{
  [encoder encodeObject:self.par forKey:@"Par"];
  [encoder encodeObject:self.yellowDistance forKey:@"YellowDistance"];

}

-(id) initWithCoder:(NSCoder*)decoder
{
  if((self=[super init]))
  {
    self.par=[decoder decodeObjectForKey:@"Par"];
    self.yellowDistance=[decoder decodeObjectForKey:@"YellowDistance"];
   }
  return  self;
}
@end

CourseObject.h
#import <Foundation/Foundation.h>
#import "HoleObject.h"

@interface CourseObject : NSObject

@property(nonatomic,strong)NSString* courseName;
@property(nonatomic,strong)NSString* courseAddress;
@property(nonatomic,strong)HoleObject* hole1;
@property(nonatomic,weak)HoleObject* hole2;
etc...
@end

CourseObject.m
#import "CourseObject.h"

@implementation CourseObject

@synthesize
courseName=_courseName,
courseAddress=_courseAddress,
hole1=_hole1,
 etc;

-(void) encodeWithCoder:(NSCoder*)encoder
{
  [encoder encodeObject:self.courseName forKey:@"CourseName"];
  [encoder encodeObject:self.courseName forKey:@"CourseAddress"];
  [encoder encodeObject:self.hole1 forKey:@"Hole1"];
  etc;  
}

-(id) initWithCoder:(NSCoder*)decoder
{
  if((self = [super init]))
  {
    self.courseName=[decoder decodeObjectForKey:@"CourseName"];
    self.courseAddress=[decoder decodeObjectForKey:@"CourseAddress"];
    self.hole1 = [decoder decodeObjectForKey:@"Hole1"];
    self.hole2 = [decoder decodeObjectForKey:@"Hole2"];
etc;
  }
  return self;
}   

@end

然后在我的主视图控制器..

- (void)viewDidLoad
{
    [super viewDidLoad];


  allCourses=[[NSMutableArray alloc] initWithCapacity:2];
  CourseObject*thisCourse;

  thisCourse=[[CourseObject alloc]init];
  thisCourse.courseName=@"Branston";
  thisCourse.courseAddress=@"The World";

  thisCourse.hole1.par=@"4";

  thisCourse.hole1.yellowDistance=@"336";

但如果我然后尝试和NSLog thisCourse.hole1.par我得到null?

感谢您的光临。

1 个答案:

答案 0 :(得分:0)

花了一些时间尝试不同的东西,因为很明显Null显示对象没有被正确创建..发现[[CourseObject alloc] init]实际上没有为对象做任何事情对象“和我需要为所有18个洞做course.hole1 = [[HoleObject alloc] init] ... ...有点繁琐,但似乎工作..