简体   繁体   中英

String formatting, varargs and EXEC_BAD_ACCESS

I have two methods in my class called TestClient

-(void)log:(NSString *)logMessage, ... 
{
    va_list ap;
    va_start(ap, logMessage);
    [self log:logMessage withParameters:ap];
    va_end(ap);
}

-(void)log:(NSString *)logMessage withParameters:(va_list)valist 
{
    NSString *formattedString = [[NSString alloc] initWithFormat:logMessage arguments:valist]; //Crashes here
    [self callMethod:@"log" withParams:formattedString, nil]; //Calls my method.
}

Here is my unit test:

-(void)testWtfCondition
{
    int test = 1;
    NSString *test2 = @"wtf";
    [proxy log:@"This is a test: %@ %@",test, test2];
}

My unit test crashes at the NSString formattedString line with EXEC_BAD_ACCESS. Am I doing something wrong with string formatting or varargs here? Is it because I'm trying to do a format with an int?

%i (or %d) - if you want to print integers

 [proxy log:@"This is a test: %i %@",test, test2];

%@ - will call [description] on class you want to print. For build-in variable types like float, int you need to cannot use it, since they are not objects.

有关更多字符串格式,您可以查看字符串编程指南

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