0

作为我的新手,我有点了解如何使用点符号创建和访问对象的属性。例如,我有一个带有属性 courseName 的对象 golfCourse,所以 golfCourse.courseName=@"My Course" 可以正常工作。我的问题是,如果我创建一个包含 Par 和 Distance 的“holeObject”并在我的 Course 对象中创建 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 我会得到空值吗?

感谢您的关注。

4

1 回答 1

0

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

于 2013-02-08T15:20:35.180 回答