Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/objective-c/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 在目标c中声明对象数组_Ios_Objective C_Arrays_Object_Nsarray - Fatal编程技术网

Ios 在目标c中声明对象数组

Ios 在目标c中声明对象数组,ios,objective-c,arrays,object,nsarray,Ios,Objective C,Arrays,Object,Nsarray,我正在研究下面的objective c示例代码。我的问题是,当创建一个以数组作为参数的方法时,-(int)match:(NSArray*)otherCards这是否意味着该数组中的对象是卡片,因为它是在Card.h中声明的?我不明白if([card.contents isqualtostring:self.contents])中的卡是从哪里来的。非常感谢你的帮助  Card.h #import <Foundation/Foundation.h> @interface Car

我正在研究下面的objective c示例代码。我的问题是,当创建一个以数组作为参数的方法时,
-(int)match:(NSArray*)otherCards
这是否意味着该数组中的对象是卡片,因为它是在
Card.h
中声明的?我不明白
if([card.contents isqualtostring:self.contents])
中的
卡是从哪里来的。非常感谢你的帮助

 Card.h
  #import <Foundation/Foundation.h>
  @interface Card : NSObject
  @property (strong, nonatomic) NSString *contents;
  @property (nonatomic, getter=isChosen) BOOL chosen;
  @property (nonatomic, getter=isMatched) BOOL matched;
  - (int)match:(NSArray *)otherCards;
  @end

Card.m
interface Card()
@end
@implementation Card
- (int)match:(NSArray *)otherCards
{
     int score = 0;
     if ([card.contents isEqualToString:self.contents]) {
        score = 1;
}
  return score;
}
@end
 卡片
#进口
@接口卡:NSObject
@属性(强,非原子)NSString*内容;
@选择属性(非原子,getter=isChosen);
@属性(非原子,getter=isMatched)布尔匹配;
-(int)匹配:(NSArray*)其他卡;
@结束
卡片
接口卡()
@结束
@实施卡
-(int)匹配:(NSArray*)其他卡
{
智力得分=0;
if([card.contents IsequalString:self.contents]){
得分=1分;
}
返回分数;
}
@结束

在此代码中未定义。它不会编译,除非它是一个全局常量或其他东西。另外,
otherCards
match:
中未使用

我怀疑这段代码应该在一个循环中,可能是这样的:

- (int)match:(NSArray *)otherCards
{
    int score = 0;

    for (Card *card in otherCards) {
        if ([card.contents isEqualToString:self.contents]) {
            score++;
        }
    }

    return score;
}

不,编译器不检查NSArray的内容。您可以将任何类型的对象放入其中,因此应始终检查对象是否为您想要的类型


而且,正如Aaron所说,代码不会编译…

谢谢Aaron!那么在像您那样添加for循环之后,代码应该能够编译了?我的意思是,对于
Card*Card
,它定义了一个方法,该方法将Card对象的NSArray作为参数?我一直在使用Java。在这种情况下,我不确定是否可以使用变量,比如数组
otherCards
,而不指定数组中的内容。Objective-C数组不是键入的。我的示例代码假定数组中填充了
Card
对象,但如果其中有其他对象,
Card.contents
将导致崩溃(除非其他对象也有
contents
属性)您可以使用
respondsToSelector:
iskindof类:
在运行时验证方法实现或类成员身份。(值得注意的是,Swift数组是键入的,与Obj-C数组不同。)要求我们推荐或查找书籍、工具、软件库、教程或其他非现场资源的问题与堆栈溢出无关