如何将宏NSString转换为NSURL

时间:2014-08-31 09:44:44

标签: ios objective-c cocoa-touch

#define string = @"http://rtchubs.com/Client/PhotoStreamer/SaveRating.php?RateID=%@&&Rate=%@&&Photoid=%@"

如何将字符串转换为URL格式?

2 个答案:

答案 0 :(得分:1)

定义这些宏

#define STRING @"http://rtchubs.com/Client/PhotoStreamer/SaveRating.php?RateID=%@&&Rate=%@&&Photoid=%@"
#define URL_FROM_PARAMETER(_rateId_, _rate_, _photoId_) [NSURL URLWithString:[NSString stringWithFormat:STRING, _rateId_, _rate_, _photoId_]]

用法

id rateId = @"rateid", rate = @"rate",photoId = @"photoid";
NSURL *url = URL_FROM_PARAMETER(rateId, rate, photoId);
NSLog(@"%@", url);

输出:

http://rtchubs.com/Client/PhotoStreamer/SaveRating.php?RateID=rateid&&Rate=rate&&Photoid=photoid

答案 1 :(得分:0)

我认为只是创建一个纯粹的帮助函数,您不必担心如何使用URL路径在整个代码库中构建正确的URL。

// .h
extern NSURL *TLARateURL(NSString *rateID, NSString *rate, NSString *photoID);

// .c/m
NSURL *TLARateURL(NSString *rateID, NSString *rate, NSString *photoID) {
  static NSString *format = @"http://rtchubs.com/Client/PhotoStreamer/SaveRating.php?RateID=%@&&Rate=%@&&Photoid=%@";
  return [NSURL URLWithString:[NSString stringWithFormat:format, rateID, rate, photoID]];
}