简体   繁体   English

iOS / Objective-C:将NSString对象添加到NSMutableArray,NSMutableArray为(空)

[英]iOS/Objective-C: Adding NSString object to NSMutableArray, NSMutableArray is (null)

- (void)webViewDidFinishLoad:(UIWebView *)webView {
if (urlIndex == maxIndex) { 
    maxIndex = maxIndex + 1;

    NSString* sURL = webpage.request.URL.absoluteString;

    [urlHistory addObject:sURL];
    NSLog(@"%d: %@", urlIndex, [urlHistory objectAtIndex:urlIndex]);
    NSLog(@"%d: %@", urlIndex, webpage.request.URL.absoluteString);


    [sURL release];

    urlIndex = urlIndex + 1;
}
else {
    [urlHistory insertObject:webView.request.URL.absoluteString atIndex:(urlIndex - 1)];
}
}

This line 这条线

    NSLog(@"%d: %@", urlIndex, [urlHistory objectAtIndex:urlIndex]);

prints (null), while as this line 打印(空),而与此行

    NSLog(@"%d: %@", urlIndex, webpage.request.URL.absoluteString);

prints the actual URL. 打印实际的URL。

On my initWithNibName I have: 在我的initWithNibName上,我有:

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
self = [super initWithNibName:@"Tab1ViewController" bundle:nil];

if (self) {
    urlHistory = [[NSMutableArray alloc] init];
    urlIndex = 0;
    maxIndex = 0;
}

return self;
}

But I still keep getting (null) when I access my array. 但是当我访问数组时,我仍然保持(null)。 Why is that? 这是为什么?

It sounds like your urlHistory object is nil . 听起来您的urlHistory对象为nil Calling -objectAtIndex: on a nil object will return nil . nil对象上调用-objectAtIndex:将返回nil You probably forgot to initialize urlHistory in your -init , or you're not actually calling the -init method you think you are (eg if your VC is loaded from a nib it will be using -initWithCoder: instead of -initWithNibName:bundle: ). 您可能忘记了在-init初始化urlHistory ,或者实际上并未调用您认为自己的-init方法(例如,如果从笔尖加载VC,它将使用-initWithCoder:而不是-initWithNibName:bundle: )。

For the record, if -objectAtIndex: on an NSArray ever returns nil , it means the array itself is nil . 作为记录,如果NSArray上的-objectAtIndex:返回nil ,则表示数组本身为nil Since NSArray cannot store nil , -objectAtIndex: with a valid index will never return nil , and -objectAtIndex: with an invalid index will throw an exception. 由于NSArray无法存储nil ,具有有效索引的-objectAtIndex:永远不会返回nil ,而具有无效索引的-objectAtIndex:将会抛出异常。 So the only way for -objectAtIndex: to return nil is if the method itself is never actually called. 因此, -objectAtIndex:返回nil的唯一方法是从未真正调用过方法本身。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM