简体   繁体   中英

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.

// 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];

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];
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM