2016-07-07 67 views
-4

希望是一個非常簡單的問題。正如你可以在我的代碼中看到的,我在viewdidload中的代碼中設置了兩個NSArray。問題是我無法在viewDidLoad之外訪問這兩個數組。有沒有辦法解決這個問題,讓我可以在viewDidLoad之外填充我的cell.textlabel.text?NSArray在viewDidLoad之外無法訪問

代碼如下:

- (void)viewDidLoad { 
    [super viewDidLoad]; 

    NSURLSession *session = [NSURLSession sharedSession]; 

    //URLText is from previous VC see .h file. 
    NSURLSessionDataTask *dataTask = [session dataTaskWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://www.test.com/%@/%@.json", _URLText, _URLText]] completionHandler:^(
                                                   NSData *data, 
                                                   NSURLResponse *response, 
                                                   NSError *error) { 
     NSDictionary *vDB = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil]; 

     NSArray *amountOfV = [vechileDB valueForKeyPath:@"amount"]; //how to assign nsstring from dictionary. 
     NSArray *makeOfV = [vDB valueForKeyPath:@"make"]; 

     NSLog(@"%@ %@", makeOfV, amountOfV); 


    }]; 

    //Run the completed task. 
    [dataTask resume]; 

} 
+4

將他們從viewDidLoad中的入類定義。並閱讀一本關於編程的初學者書籍;-) – Gruntcakes

+0

對於您在執行該操作後遇到的問題,請參閱[在塊執行後返回NULL的變量](http://stackoverflow.com/q/13350108) –

+0

我不喜歡像「讀一本初學者書」這樣的說法。這並沒有什麼幫助,雖然它對某些人來說可能很有趣,但對於提問的人來說,這當然並不好笑。 TBH,它有點像我欺負的一種形式。 :-( – ghostatron

回答

3

您可以定義數組作爲在.m文件的屬性,下面看到的,那麼就只是引用數組self.amountOfV。

@interface YourClass() 
@property (nonatomic) NSArray *amountOfV; 
@property (nonatomic) NSArray *makeOfV; 
@end 

@implementation YourClass 
... 

如果您有興趣,領域上有很好的房產屬性文章,https://realm.io/news/tmi-objective-c-property-attributes/

1

可以作爲如屬性同時聲明數組:

@property (strong, nonatomic) NSArray *amountOfV; 

,並呼籲他們爲self.amountOfV