【问题标题】:How to use NSArray in objective C. Card Deck on iPhone如何在 Objective C 中使用 NSArray。iPhone 上的 Card Deck
【发布时间】:2013-01-11 14:42:06
【问题描述】:

我是 Objective C 的新手,我似乎无法找到如何做到这一点(如果可能的话)。

我有一个NSArray,里面有 4 张卡片(卡片 = 我自己的班级),我想将标签的文本设置为我的卡片对象所持有的 NSString

在 Java 中,我会这样做: 如果我有一个包含 4 张卡片的卡片数组,并且 theLabel 是一个字符串。

theLabel = deck[2].getLabel();

这似乎不适用于 Objective C。到目前为止,我在 Objective C 中的代码:

- (IBAction)nextCard:(id)sender {
    theLabel.text = [deck objectAtIndex:j].getLabel;
    theImage.image = [deck objectAtIndex:j].getImage;
}

每次我点击 iPhone 上的按钮时都会调用 nextCard。 j 是一个普通的 int,它将跟踪显示哪张卡片。

创建数组时是这样的:

- (void)viewDidLoad
{
    [super viewDidLoad];

    ah = [[Card alloc]init];
    [ah setLabel:@"label1"];
    [ah setCardImage: [UIImage imageNamed:@"3.png" ]];

    as = [[Card alloc]init];
    [as setLabel:@"label2"];
    [as setCardImage: [UIImage imageNamed:@"2.png" ]];

    ac = [[Card alloc]init];
    [ac setLabel:@"labbel3"];
    [ac setCardImage: [UIImage imageNamed:@"1.png" ]];

    ad = [[Card alloc]init];
    [ad setLabel:@"label4"];
    [ad setCardImage: [UIImage imageNamed:@"4.png" ]];

    deck = [NSMutableArray arrayWithCapacity:25];
    [deck addObject:ah];
    [deck addObject:as];
    [deck addObject:ac];
    [deck addObject:ad];
}

所以我基本上希望能够使用方法 ob 对象存储在 NSArray 中。

非常感谢您的回答,在此先感谢!

【问题讨论】:

  • 可以给我们看看你的卡片等级吗?至少是标题?当前代码表明您可能正在尝试将 UILabel 设置为 NSString...

标签: objective-c nsarray


【解决方案1】:

在 Objective-C 中,生成的 getter 没有 get 前缀,所以你可以这样使用它:

theLabel = deck[2].label;

或者:

theLabel= [deck[2] label];

【讨论】:

    【解决方案2】:

    检查一下:

    [deck objectAtIndex:0].label;
    

    或:

    [[deck objectAtIndex:0] label];
    

    或:

    [[deck objectAtIndex:0] yourMethodWithParameter:@"foo"];
    

    【讨论】:

      【解决方案3】:

      在 Objective-C 中,大多数情况下访问器方法是自动生成的。 假设我们有一个名为“object”的属性 getter 方法不是这样命名的 getObject ,其中“object”是您要访问的属性。 它只是通过属性的名称来命名,像这样object

      所以在你的情况下应该是这样的:

      NSString *theLabelString = [[deck objectAtIndex:j] label];
      //or this:
      NSString *theLabelString = [deck[j] label];
      //or this:
      NSString *theLabelString = deck[j].label;
      

      【讨论】:

        猜你喜欢
        • 2021-02-07
        • 2016-02-13
        • 2010-10-09
        • 2011-11-05
        • 2023-03-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-07-26
        相关资源
        最近更新 更多