index 0 beyond bounds for empty array while getting to the documents directory

对着背影说爱祢 提交于 2019-12-25 04:57:11

问题


I use the following code to get to the documents directory.

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];

Why would my app be crashing with the following message?

*** -[__NSArrayI objectAtIndex:]: index 0 beyond bounds for empty array

I can't see how my NSArray (immutable array) can be empty. The function is supposed to return the documents folder in an array. Any ideas?


回答1:


1) Are you sure the crash is there?

2) Not totally related but can help.




回答2:


The array returned by NSSearchPathForDirectoriesInDomains has zero elements in it. It's empty. Exactly what the error message says.




回答3:


Not answering why, but since Xcode 5:

NSString *documentsDirectory = [paths firstObject];

If it's empty, it won't raise an exception, it will return nil. No crash.




回答4:


Try using NSHomeDirectory() instead... It is a nicer way to get the applications home directory.

Note: If you are after the Documents Directory then you may need to append @"Documents/" to the string



来源:https://stackoverflow.com/questions/12938962/index-0-beyond-bounds-for-empty-array-while-getting-to-the-documents-directory

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!