For my beginner's level independent study of Objective-C, I was asked to add a counter to a class, so that each time a method was used on it, it would ++. However, I misinterpreted this as "Each time the method the method is called, ++." After realizing how to do what was asked of me, I pondered how I could fashion a method that would return a counter in addition to what the method was called to return. If I were to use a static int in addition to variable++; on each call of the method, how can I extract that value o开发者_Go百科f variable in my main program?
Example code from comment:
-(Fraction *) add: (Fraction *) f {
static int fractaddcount;
fractaddcount++;
Fraction *result = [[Fraction alloc] init];
result.numerator = numerator * f.denominator + denominator * f.numerator;
result.denominator = denominator * f.denominator;
return result;
}
Make fractaddcount
an instance variable and initialize it to 0 in the init
method. Then it can be accessed by other methods in the class.
Additionally if you make it a property
other classes will be able to access it. You can even make the property
readonly in the .h file and read/write in the .m file (class extension).
Example:
in .h:
@property (non atomic, readonly, assign) int fractaddcount;
in .m:
in class extension:
@Interface TheClassName ()
@property (non atomic, readwrite, assign) int fractaddcount;
@end
in the implementation:
@synthesize fractaddcount;
in init: This is somewhat optional since when the class is instantiated the ivars are cleared to nil (0).
fractaddcount = 0;
in your code:
self.fractaddcount = self.fractaddcount + 1;
精彩评论