2014-02-07 44 views
0

我很新的目標C在一般...xcode使用變量

我想知道如何在視圖控制器中使用*變量,並將其添加到Web視圖URL。 Bellow是一個UIWebViewer,它加載「site.com/something.php」...隨着我想要插件到URL「?uuid =(UUID Variable here)」。

對不起...我更習慣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]; 
} 
+0

您正在創建一個字符串的修改版本的任何值,所以調用'stringByAppendingString:'(或'stringWithFormat:'。 – matt

+0

那麼你需要學習的第一件事就是'xcode'是一個'IDE',這個問題跟它沒有任何關係 – Popeye

+0

那麼@Popeye如果涉及到,它與UIWebView無關......! – matt

回答

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:

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,它只是返回字符串本身,但是您會注意到您也可以在其中放置很多其他類型的對象...實際上,從NSObject繼承的每個對象都有一個默認的description方法)。

+0

什麼?你是在模擬器還是在實際設備上運行它? – nhgrif