0

可能重复:
访问数组对象

我的 xib 文件中有一个包含图像和图像视图的数组。现在,我想在我的图像视图中查看我的数组包含的第一个对象(图像)。我试着做了几个小时,但我没有成功。我该怎么做??

mt数组减速:

    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];

我尝试使用的代码:

imgView = [[UIImageView alloc] initWithImage:[photoArray objectAtIndex:0]];

谢谢!!

4

2 回答 2

1

您的问题的答案非常简单,如果您不熟悉这一切,请尝试分步进行。

array: photoarray 
imageView in xib : imgView
imgView =[UIImageView alloc]init];
imgView.image=[UIImage imageNamed:[photoarray objectatindex:0]];

这将满足您的问题的目的。

于 2012-10-24T23:36:24.390 回答
0

您的照片数组不包含图像,它包含自定义 PhotoItem 对象。您需要从该对象中获取 UIImage 。我假设您有一个属性集,可能名为 photo on PhotoItem。你需要打电话给这个。

imgView = [[UIImageView alloc] initWithImage:[[photoArray objectAtIndex:0] photo]];

// or

imgView = [[UIImageView alloc] initWithImage:[photoArray objectAtIndex:0].photo];

更新

您必须具有属性才能访问有关对象的信息。您需要重建您的 PhotoItem 类,以便为您想要访问的内容(如照片、姓名和摄影师)提供属性。无法以您尝试的方式访问实例变量。

// PhotoItem.m

@interface PhotoItem : NSObject
{
     // Instance Variables aren't accessible outside of the class.
}

@property (nonatomic, strong) UIImage *photo;
@property (nonatomic, strong) NSString *name;
@property (nonatomic, strong) NSString *photographer;

- (id) initWithPhoto:(UIImage)image name:(NSString*)stringA photographer:(NSString*)stringB;

而且你可能也需要重写你的 init 。

// PhotoItem.h

@implementation PhotoItem

@synthesize photo, name, photographer;

- (id) initWithPhoto:(UIImage)image name:(NSString*)stringA photographer:(NSString*)stringB
{
    self = [super init];
    if (self) {
         photo = image;
         name = stringA;
         photographer = stringB;
    }
}

然后访问它的任何东西

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

photo1.photo // returns UIImage
photo1.name // returns NSString
photo1.photographer // returns NSString

因此,如果它们是数组中的对象,它将是

[photoArray objectAtIndex:0] // returns your PhotoItem Object
[[photoArray objectAtIndex:0] photo] // returns that PhotoItem Object then gets the photo out of it returning a UIImage in total.
于 2012-06-02T12:27:55.583 回答