objective c - Why can we use an instance of a custom/foundation class in the implementation of a method without first doing alloc and init for the instance? -


this question based on code first lecture in stanford ios series 2014 (objective - c).

we created class called card includes method named match: used determine how different cards match against 1 in game, , method takes argument nsarray called *othercards , use instance of card called *card iterate through array in implementation of method.

my question - how can declare instance of our class card i.e *card , use iterating variable in loop without first allocating , instantiating it? in same vein, how can declare *othercards instance of nsarray , use in cycling through of loop before allocated , initialised also?

i realise might done later in code, why isn't compiler throwing @ least warning this?

here code:

//card.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;        //card.m    #import "card.h"      @implementation card     - (int)match:(nsarray *)othercards     {           int score = 0;      (card *card in othercards) {      if ([card.contents isequaltostring:self.contents ])     {             score = 1;         }          }          return score;     }       @end 

i think question loop:

for (card *card in othercards) {     ... } 

how can declare *othercards instance of nsarray , use it

you don't need alloc , init othercards because supplied parameter function match. caller responsible initializing it. can't dodge initialization, it's done elsewhere:

card * mycard = ...               // init varible here nsarray * othercards = ...        // init array here int n = [mycard match:othercards] // othercards initialized. don't need                                    // again inside method 

how can declare instance of our class card i.e *card , use iterating variable in for loop

card not new object. points existing objects inside othercards array, hence no need alloc , init.

you did declare card pointer of type card in for loop: for (card * card in othercards). syntactic sugar make code more concise. can long way if want:

card * card; (card in othercards) {     // } 

Comments