问题描述:

I have a question regarding for..in (for loop) in Objective-C

below is my header and implementation file:

==header==

#import <Foundation/Foundation.h>

@interface Card : NSObject

@property(strong, nonatomic) NSString *contents;

@property(nonatomic, getter = isMatched) BOOL matched;

@property(nonatomic, getter = isChosen) BOOL chosen;

-(int)match: (NSArray *)otherCards;

@end

==implementation==

#import "Card.h"

@implementation Card

-(int)match: (NSArray *) otherCards{

int score =0;

for(Card* card in otherCards){

if ([card.contents isEqualToString:self.contents]) {

score =1;

}

}

return score;

}

@end

  1. In the implementation file (inside the for loop), what does the self in self.contents referring to ?

  2. Does the for loop intend to compare one card in the array to the rest of the other cards in the array?

  3. How would you write the loop in the conventional iteration for(int i=0, i<n; i++).

    Assuming n is the size of the loop

Thank you

网友答案:

1) The card that received the match message.

2) No, it compares one card (self) with an array of cards (otherCards).

3) Here's the equivalent code using an index:

for(int i = 0; i < [otherCards count]; i++)
    if([otherCards[i].contents isEqualToString:self.contents]) {
        score = 1;
    }
}
网友答案:
  1. self refers to the object that the match method was called on. self.contents refers to this property defined in your header: @property(strong, nonatomic) NSString *contents;

  2. The loop compares all of the cards in the array otherCard to the card that the match message was sent to.

3.

for(int i=0; i< [otherCards count]; i++)
{
    if ([otherCards[i].contents isEqualToString:self.contents]) 
    {
        score =1;
    }
}
相关阅读:
Top