elementsense
elementsense

Reputation: 1540

How to create a method in Objective-C that takes a NSString stringWithFormat as a parameter?

I am not sure if the headline is understandable. What I want is to make a convinient method that works like the NSLog method and combines the lines below?

This is what I have at the moment :

NSString *out = [NSString stringWithFormat:@"something %d,%d",1,2];
[self showLog:out];

How would a method like this look like in the definition ?

- (void) showLog:(NSString *) data;

Thanks

Upvotes: 3

Views: 4440

Answers (4)

vakio
vakio

Reputation: 3177

https://developer.apple.com/library/content/qa/qa1405/_index.html

- (void) showLog: (id) data, ...;

Upvotes: 2

Pir Fahim Shah
Pir Fahim Shah

Reputation: 10633

If you want to create a method which take String as an argument, then use this code it will help you.

#import <Foundation/Foundation.h>
@interface SampleClass:NSObject
  //Method declaration
- (void) functn:(NSString*)str;
@end

@implementation SampleClass
  //<<<<<<<<<<-- Function to print UserName -->>>>>>>>>>>>>>>
- (void)functn:(NSString*)str
  {
  NSLog(@"Your Name is %@",str);
  }
@end
int main ()
{
 SampleClass *sampleClass = [[SampleClass alloc]init];
 /* calling a method to get max value */
 NSString *yourName=@"Pir fahim shah";
 [sampleClass functn:yourName];
 return 0;
}

Upvotes: 0

Something like this?

NSString *out = [NSString stringWithFormat:@"something %d,%d",1,2];
[self showLog:out];

- (void)showLog:(NSString*)data{
     NSLog(@"%@", data);
}

Just ask for more help if you need it :)

or feel free to clarify your question if i am mistaking what you need ;)

Best regards Kristian

Upvotes: 1

JeremyP
JeremyP

Reputation: 86691

In the interface,

-(void) showLog: (NSString*) formatSpecifier, ...;

In the implementation

-(void) showLog: (NSString*) formatSpecifier, ...
{
    va_list formatArgs;
    va_start(formatArgs, formatSpecifier);
    NSString* logMessage = [[NSString alloc] initWithFormat: formatSpecifier arguments: formatArgs];
    va_end(formatArgs);

    // Do want you need to to output the string.

    [logMessage release];
}

Upvotes: 7

Related Questions