Crystal
Crystal

Reputation: 29458

Pass by value in Objective-C?

I'm looking at understanding objective-c and I came into a problem in tapping the screen and incrementing the count variable which I store in my appdelegate.

- (void)updateLabel:(NSInteger)num {
    NSString *s = [[NSString alloc] initWithFormat:@"%@", num];
    countLabel.text = s;
    [s release];
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    TestAppDelegate *aDel = (TestAppDelegate *)[UIApplication sharedApplication].delegate;
    aDel.count++;
    NSInteger num = aDel.count;
    [self updateLabel:num];
}

I get the EXC_BAD_ACS which to me says I'm trying to access something I'm not. It looks like I cannot send updateLabel the num variable because the scope of the primitive type goes away at the end of the method and then when updateLabel tries to access it, I get the error? I wanted to know if I understood this concept correctly. Thanks.

Upvotes: 1

Views: 499

Answers (2)

taskinoor
taskinoor

Reputation: 46027

// format specifier for integer is %d, not %@
NSString *s = [[NSString alloc] initWithFormat:@"%d", num];

num is not out of scope here. You are passing it by value to updateLabel. Please also check that countLabel is not already released when you are calling updateLabel.

And you can pass aDel.count directly to the updateLabel. There is no need of temporary num variable.

[self updateLabel:aDel.count];

Upvotes: 2

zoul
zoul

Reputation: 104065

The problem might be that NSInteger is not an object, see its definition by cmd-clicking the keyword:

#if __LP64__ || TARGET_OS_EMBEDDED || TARGET_OS_IPHONE …
typedef long NSInteger;
typedef unsigned long NSUInteger;
#else
typedef int NSInteger;
typedef unsigned int NSUInteger;
#endif

Which means that your method to update the label should look a bit like this:

- (void) updateLabel: (NSInteger) num {
    countLabel.text = [NSString stringWithFormat:@"%i", num];
}

Upvotes: 1

Related Questions