Question

I have some predefined string formats that I would like to fill values to, at runtime, and present to the user. I want to store them as either constants or defines, whichever suits better.

Something like:

@% has sent you a message on @%-@%-@%.

At runtime, above will get sender's name and mm-dd-yy to prepare required string:

James Bond has sent you a message on 12-31-2050.

Can anyone point to code to implement such kind of thing?

EDIT: Contrary to what many (especially the downvoters!) believe:

This is not simply a string formatting question. It is posted to ensure:

  • the string format storage is memory efficient (static vs define vs anything else) because I want to store the format permanently, not just for the time of usage
  • the value substitution at runtime is time efficient (stringWithFormat vs other options)
Was it helpful?

Solution 2

You can do like this:

At top,

#define MESSAGE @"%@ has sent you a message on %@-%@-%@."

Then whenever you want to use that message, use below syntex:

[NSString stringWithFormat:MESSAGE, <sender_name>, <date>, <month>, <year>];

sender_name,date,month,year are dynamic values.

Hope, you got an idea.

Happy Coding!

Cheers!

OTHER TIPS

try this.. May be it will help you.

 NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"dd-MM-yyyy"];
    NSDate *now = [[NSDate alloc] init];

    NSString *theDate = [dateFormat stringFromDate:now];
     NSLog(@"theDate..%@",theDate);
    NSString *str = @"yourString";
    NSString *new =  [NSString stringWithFormat:@"%@ has sent you a message on %@", str, theDate];

Use [NSString stringWithFormat:@"%@ has sent you a message on %@", who, date]

fIrst of all,you need to get current date

NSDateFormatter *date= [[NSDateFormatter alloc] init];
    [date setDateFormat:@"MM-dd-yyyy"];
    NSDate *thisDate= [[NSDate alloc] init];

NSString *currentDate= [date stringFromDate:thisDate];
 NSLog(@"Current date is..%@",currentDate);

Now you can enter any string at runtime

 NSString *strng = @"whatever kind of string which you want to add at runtime";
    NSString *newString=  [NSString stringWithFormat:@"%@ has sent you a message on %@", strng, currentDate];

The value of "newString" will provide you the required result.

Use #define messageString(x,y,z) [NSString stringWithFormat:@"%@ has sent you a message on %@-%@-%@.",x,y,z]

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top