Cocoa - calling a variational method from another variational (calling NSString stringWithFormat)

I have a problem with [NSString strigWithFormat:format], because it returns id, and I have a lot of code where I changed var NSString to another personal type. But the compiler does not bother me that there are places where NSString will be installed in another type of object.

So, I am writing the NSString category, and I want to replace all my calls with stringWithFormatby myStringWithFormat.

The code:

@interface NSString (NSStringPerso)
+ (NSString*) myStringWithFormat:(NSString *)format;
@end



@implementation NSString (NSStringPerso)
+ (NSString*) myStringWithFormat:(NSString *)format {
    return (NSString*)[NSString stringWithFormat:format];
}
@end

The compiler tells me that "Format is not a string literal and format arguments."

Do you see any way to make this work?

+3
source share
3 answers

NSStringincludes a method that takes a list of arguments from a variational function. Take a look at this feature:

void print (NSString *format, ...) {
    va_list arguments;
    va_start(arguments, format);

    NSString *outout = [[NSString alloc] initWithFormat:format arguments:arguments];
    fputs([output UTF8String], stdout);
    [output release];

    va_end(arguments);
}

, NSString *output = [[NSString alloc] initWithformat:format arguments:arguments];. , NSString /.


:

+ (NSString *)myStringWithFormat:(NSString *)format, ... {
    va_list arguments;
    va_start(arguments, format);

    NSString *formattedString = [[NSString alloc] initWithFormat:format arguments:arguments];
    va_end(arguments);

    // perform some modifications to formattedString

    return [formattedString autorelease];
}
+6

Objective-C , stringWithFormat , , argument.

EDIT: stringWithFormat - variadic . .

+1

. , !

:

.h

@interface NSString (NSStringPerso)
+ (NSString*) strWithFormatPerso:(id)firstObject, ...;
@end

.m

@implementation NSString (NSStringPerso)
+ (NSString*) strWithFormatPerso:(id)firstObject, ... {

    NSString* a;

    va_list vl;
    va_start(vl, firstObject);
    a = [[[NSString alloc] initWithFormat:firstObject, vl] autorelease];
    va_end(vl);

    return a;
}
@end
+1

Source: https://habr.com/ru/post/1785670/


All Articles