xCode使用变量

时间:2014-02-07 22:36:12

标签: objective-c nsstring nsurl

我对Objective C很新......

我想知道如何在视图控制器中使用*变量,并将其添加到Web视图URL中。 Bellow是一个UIWebViewer,它加载“site.com/something.php”......我希望它能添加到URL“?uuid =(这里是UUID变量)”。

抱歉...我更习惯PHP / Perl编码,你只需要输入“$ uuid”...... 谢谢,

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];

    NSString *UUID = [[NSUUID UUID] UUIDString];
    NSURL *myURL = [NSURL URLWithString:@"http://www.site.com/something.php?uuid="];

    NSURLRequest *myRequest = [NSURLRequest requestWithURL:myURL];

    [myWebView loadRequest:myRequest];
}

2 个答案:

答案 0 :(得分:1)

以下是您正在寻找的内容:

NSString *UUID = [[NSUUID UUID] UUIDString];
NSString *urlstr = [NSString stringWithFormat:
    @"http://www.site.com/something.php?=%@", UUID];
NSURL *myURL = [NSURL URLWithString:urlstr];

NSString的stringWithFormat:方法允许您从文字字符串和变量构建字符串。使用格式说明符将变量添加到文字字符串中。大多数格式说明符与所有其他基于C的语言相同,%d表示整数类型,%f表示浮点类型,%c表示char,等等。

对于Objective-C%@用作响应description选择器的对象的占位符,后者返回一个字符串。 (在NSString的情况下,它只返回字符串本身,但你会注意到你也可以在这里放置很多其他类型的对象......实际上,每个对象都继承自{{1} }有一个默认的NSObject方法。)

答案 1 :(得分:1)

您只需要创建一个属性来分配您想要的任何值

,这非常简单

ViewController.m

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];

    NSString *uuid = [[NSUUID UUID] UUIDString]; // Convention says that UUID should uuid

    // All we need to do now is add the uuid variable to the end of the string and we can do
    // that by using stringWithFormat:
    NSURL *myURL = [NSURL URLWithString:[NSString stringWithFormat:@"http://www.site.com/something.php?uuid=%@", uuid]];

    NSURLRequest *myRequest = [NSURLRequest requestWithURL:myURL];

    [myWebView loadRequest:myRequest];
}

Check the documentation of NSString and the class method stringWithFormat: