I am updating some old code to our new coding standards. In this code, the int
variable was incremented with the old ++
operator. Now, the int
variable is a property so using ++
isn't working so well. I'm not supposed to use dots and I'm not supposed 开发者_C百科to reference ivars directly.
int
):
declaration section
@synthesize totalHeads = _totalHeads;
further down
[self setTotalHeads:[self totalHeads] + 1];
which replaces the old code of
_totalHeads ++;
Is there a more elegant way to do this?
(apologies if this is a duplicate question, I was having a hard time figuring out good search terms)You can use the property and the postincrement operator. This code:
@interface Foo: NSObject
@property (assign) int bar;
@end
@implementation Foo
@synthesize bar;
@end
int main() {
Foo *foo = [[Foo alloc] init];
foo.bar = 3;
foo.bar++;
NSLog(@"foo.bar: %d", foo.bar);
[foo release];
return 0;
}
produces this result:
2011-06-21 21:17:53.552 Untitled[838:903] foo.bar: 4
It doesn't really matter that's a property - it's still an int and, unless you declare a different name for ivar associated with the property, you can still use totalHeads++;
If, as you've mentioned in the comments, you're not allowed to use dot syntax to access setter methods, then [self setTotalHeads:[self totalHeads] + 1];
is the only way to do it.
Coding standards that disallow use of language features under all circumstances are unproductive. Maybe you can use this example to make your case.
Based on a question about converting between NSInteger and int, I came up with the following:
- (NSInteger) incrementNSInteger: (NSInteger) nsInt byNumber: (int)increment
{
int integer = nsInt;
integer += increment;
NSInteger result = integer;
return result;
}
To use:
NSInteger one;
NSInteger two = [self incrementNSInteger: one byNumber: 1];
If you supply "byNumber" with -1, it'll decrement. Similarly, 2 increments by 2, -2 decrements by 2. (Why ++ and -- aren't sufficient baffles me).
精彩评论