iOS/Objective-C:将 NSString 对象添加到 NSMutableArray,NSMutableArray 为 (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)];
}
}
此行
NSLog(@"%d: %@", urlIndex, [urlHistory objectAtIndex:urlIndex]);
打印 (null),而此行
NSLog(@"%d: %@", urlIndex, webpage.request.URL.absoluteString);
打印实际的 URL。
在我的 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;
}
但当我访问数组时,我仍然不断收到 (null) 。这是为什么?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
听起来你的 urlHistory 对象是 nil 。对
nil
对象调用-objectAtIndex:
将返回nil
。您可能忘记在-init
中初始化urlHistory
,或者您实际上并没有调用您认为的-init
方法(例如,如果您的 VC 是从笔尖加载的,它将使用-initWithCoder:
而不是-initWithNibName:bundle:
)。根据记录,如果
NSArray
上的-objectAtIndex:
返回nil
,则意味着数组本身为nil
。由于NSArray
无法存储nil
,因此具有有效索引的-objectAtIndex:
永远不会返回nil
,并且-objectAtIndex:
索引无效将引发异常。因此,-objectAtIndex:
返回 nil 的唯一方法是方法本身从未被实际调用。It sounds like your
urlHistory
object isnil
. Calling-objectAtIndex:
on anil
object will returnnil
. You probably forgot to initializeurlHistory
in your-init
, or you're not actually calling the-init
method you think you are (e.g. if your VC is loaded from a nib it will be using-initWithCoder:
instead of-initWithNibName:bundle:
).For the record, if
-objectAtIndex:
on anNSArray
ever returnsnil
, it means the array itself isnil
. SinceNSArray
cannot storenil
,-objectAtIndex:
with a valid index will never returnnil
, and-objectAtIndex:
with an invalid index will throw an exception. So the only way for-objectAtIndex:
to return nil is if the method itself is never actually called.