0

我创建一个数组并用对象初始化它。我试图访问数组对象,但我得到一个(null)。我做错了什么?

    photoArray = [[NSMutableArray alloc] init];
    PhotoItem *photo1 = [[PhotoItem alloc] initWithPhoto:[UIImage imageNamed:@"1.jpg"] name:@"roy rest"  photographer:@"roy"];
    PhotoItem *photo2 = [[PhotoItem alloc] initWithPhoto:[UIImage imageNamed:@"2.jpg"] name:@"roy's hand" photographer:@"roy"];
    PhotoItem *photo3 = [[PhotoItem alloc] initWithPhoto:[UIImage imageNamed:@"3.jpg"] name:@"sapir first" photographer:@"sapir"];
    PhotoItem *photo4 = [[PhotoItem alloc] initWithPhoto:[UIImage imageNamed:@"4.jpg"] name:@"sapir second" photographer:@"sapir"];
    [photoArray addObject:photo1];
    [photoArray addObject:photo2];
    [photoArray addObject:photo3];
    [photoArray addObject:photo4];

我尝试通过这行代码访问其中一个对象(返回(null)):

photoName.text = [NSString stringWithFormat:@"%@", [[photoArray objectAtIndex:2] nameOfPhotographer]]

更新:photoitem的代码:

-(id)initWithPhoto:(UIImage*)image name:(NSString*)photoName photographer:(NSString*)photographerName
{
    self = [super init];
    if(self)
    {
    imageItem = image;
    name = photoName;
    nameOfPhotographer = photographerName;


    //[self setName:photoName];
    //[self setNameOfPhotographer:photographerName];
    //[self setImageItem:image];
}
return self;
}

问题是什么?

谢谢!!

4

2 回答 2

0

你应该这样做:

@property(strong, nonatomic) NSString* nameOfPhotographer;

而在initWith....

self.nameOfPhotographer = 摄影师姓名;

于 2012-06-02T18:59:05.757 回答
0

首先,确保您的 PhotoItem 接口文件与此类似:

@interface PhotoItem : NSObject
{
  UIImage *imageItem;
  NSString *name;
  NSString *photographer;
}

@property (nonatomic, retain) UIImage *imageItem;
@property (nonatomic, retain) NSString *name;
@property (nonatomic, retain) NSString *photographer;


@end

其次确保你的实现部分是这样的:

@implementation PhotoItem
@synthesize imageItem, name, photographer;

-(id)initWithPhoto:(UIImage*)image name:(NSString*)photoName photographer:(NSString*)photographerName
{
  self = [super init];

  if(self)
  {
    self.imageItem = image;
    self.name = photoName;
    self.photographer = photographerName;
  }

  return self;
}

- (NSString *)description
{
  return [NSString stringWithFormat:@"name:%@\nphotographer:%@", self.name, self.photographer];
}

@end

现在,由于 description 是您记录对象时对对象的默认调用,因此您现在可以真正轻松地诊断您的问题。

我添加了类文件来向您展示属性是多么方便。

现在,当您想访问时说出摄影师的姓名,只需执行以下操作:

photo1.photographer

好的,现在在您的代码中,不要立即将所有内容都放入数组中,而是这样做以确保一切正常:

PhotoItem *photo1 = [[PhotoItem alloc] initWithPhoto:[UIImage imageNamed:@"1.jpg"] name:@"roy rest"  photographer:@"roy"];

NSLog(@"%@", [photo1 description]);

它们实际上应该是,我给你的类代码应该可以正常工作。现在根据需要将它们全部放入一个数组中,并确保数组中的所有内容都符合要求,请执行以下操作:

NSLog(@"%@", photoArray); //Description is the default when logging an object
//An array will call the description method on each of it's containing objects

希望这可以帮助!

于 2012-06-03T06:44:34.717 回答