【问题标题】:Add Several NSStrings to NSMutableArray添加几个 NSString 到 NSMutableArray
【发布时间】:2014-09-30 03:19:28
【问题描述】:

我有一个使用 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 运行了适当的次数,但每次,数组都只保留一首诗,我预计它会逐渐增长。

【问题讨论】:

  • 那么你期待什么?每次调用 doneGotIt 时都重新初始化它(alloc init 将创建一个 new 数组)
  • self.theArray = [[NSMutableArray alloc] init];每次调用 doneGoIt 时都会定义数组,因此数组只包含最近的数据
  • 我知道这不是你的问题,但你可以通过使用 [self.theArray appendFormat:] 而不是创建 stringWithFormat: 然后将其添加到可变字符串来优化

标签: ios objective-c nsstring nsmutablearray nsurlrequest


【解决方案1】:

您每次都在创建新的数组实例。就是这样,你得到了最后一部分。

- (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);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-16
    • 1970-01-01
    相关资源
    最近更新 更多