-3

我有一些预定义的字符串格式,我想在运行时填充值并呈现给用户。我想将它们存储为constantsdefines,以更适合的方式存储。

就像是:

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

在运行时,上面将获取发件人的姓名和 mm-dd-yy 以准备所需的字符串:

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

谁能指出实现这种事情的代码?

编辑:与许多人(尤其是反对者!)相信的相反:

这不仅仅是一个字符串格式问题。发布它是为了确保:

  • 字符串格式存储是内存高效的(静态 vs 定义 vs 其他),因为我想永久存储格式,而不仅仅是使用时间
  • 运行时的值替换是高效的(stringWithFormat 与其他选项)
4

5 回答 5

2

试试这个..也许它会帮助你。

 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];
于 2013-01-30T10:29:50.073 回答
1

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

于 2013-01-30T10:18:36.993 回答
1

你可以这样做:

在顶部,

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

然后,每当您想使用该消息时,请使用以下语法:

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

sender_name,date,month,year 是动态值。

希望,你有一个想法。

快乐编码!

干杯!

于 2013-01-30T10:38:43.833 回答
1

首先,您需要获取当前日期

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);

现在您可以在运行时输入任何字符串

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

“newString”的值将为您提供所需的结果。

于 2013-01-30T10:56:20.517 回答
0

使用 #define messageString(x,y,z) [NSString stringWithFormat:@"%@ 已在 %@-%@-%@ 上向您发送了一条消息。",x,y,z]

于 2013-01-30T10:46:00.380 回答