将几个NSStrings添加到NSMutableArray

时间:2014-09-30 03:19:29

标签: ios objective-c nsstring nsmutablearray nsurlrequest

我有一个使用for循环运行多次的API GET请求。我成功地能够从中创建一些NSStrings,但鉴于循环,我需要一个很好的方法将它们存储在一起。所以,在connectionRequest结束时,我让它运行另一个方法,在那里我将NSString添加到NSMutableArray。但是,当我检查NSMutableArray的内容时,它只是那里最新的NSString。我错过了什么?

- (void)viewWillAppear:(BOOL)animated {

   for(int i = 0; i< self.theNumber; i++) {
        [self getQuote];
    }


}
-(void) getQuote {




    NSString *bringitalltogether = @"URLOFAPI";
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:bringitalltogether]
                                                           cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:60];
    [request setHTTPMethod:@"GET"];


    NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
    [connection start];

}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {

    NSMutableDictionary *allResults = [NSJSONSerialization
                                       JSONObjectWithData:data
                                       options:NSJSONReadingAllowFragments
                                       error:nil];
    NSArray *book = [allResults valueForKey:@"bookname"];
    self.bookstring = [book objectAtIndex:0];
    NSArray *chapter = [allResults valueForKey:@"chapter"];
    self.chapterstring = [chapter objectAtIndex:0];

    NSArray *verse = [allResults valueForKey:@"verse"];
    self.versestring = [verse objectAtIndex:0];

    NSArray *text = [allResults valueForKey:@"text"];
    self.textstring = [text objectAtIndex:0];

    [self doneGotIt];
   }
- (void) doneGotIt {
    self.theArray = [[NSMutableArray alloc] init];
    NSString *doIt = [NSString stringWithFormat:@"%@ - %@ %@:%@", self.textstring, self.bookstring, self.chapterstring, self.versestring];
    [self.theArray addObject:doIt];
    NSLog(@"%@", self.theArray);
}

控制台显示NSLog运行了适当的次数,但是每次,当我希望它逐渐增长时,数组只保留一节。

1 个答案:

答案 0 :(得分:4)

您每次都在创建新的数组实例。多数民众赞成,你们最后一部分。

- (void) doneGotIt {
//Create array only once if not yet created in memory
    if (!self.theArray) {

        self.theArray = [[NSMutableArray alloc] init];

    }

    NSString *doIt = [NSString stringWithFormat:@"%@ - %@ %@:%@", self.textstring, self.bookstring, self.chapterstring, self.versestring];
    [self.theArray addObject:doIt];
    NSLog(@"%@", self.theArray);
}