【问题标题】:initWithContentsOfFile:encoding:error: - NSInvalidArgumentExceptioninitWithContentsOfFile:encoding:error: - NSInvalidArgumentException
【发布时间】:2011-12-08 15:37:46
【问题描述】:

我想我在这里遗漏了一些非常基本的,但它就在这里。

XCode 中的内联帮助告诉我 initWithContentsOfFile: 已弃用

NSMutableDictionary *myDict = [[NSMutableDictionary alloc] initWithContentsOfFile:plistPath];

应该使用 initWithContentsOfFile:encoding:error:

NSMutableDictionary *myDict = [[NSMutableDictionary alloc] initWithContentsOfFile:plistPath encoding:NSUTF8StringEncoding  error:NULL];

我的问题是 initWithContentsOfFile: 工作正常,而下面的代码引发错误。

NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"prefs" ofType:@"plist"];
Load preferences into symbol dictionary
NSMutableDictionary *myDict = [[NSMutableDictionary alloc] initWithContentsOfFile:plistPath encoding:NSUTF8StringEncoding  error:NULL];

错误:

2011-12-08 16:27:12.209  -[__NSPlaceholderDictionary initWithContentsOfFile:encoding:error:]: unrecognized selector sent to instance 0x4b2a370
2011-12-08 16:27:12.212 *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSPlaceholderDictionary initWithContentsOfFile:encoding:error:]: unrecognized selector sent to instance 0x4b2a370'

【问题讨论】:

  • 你的目标是什么版本的IOS。据我所知,2.0 版之后的所有内容都具有 [[NSMutableDictionary alloc] initWithContentsOfFile:filePath]。文档是here。我在 NSDictionary 的文档中没有看到 initWithContentsOfFile:encoding:error 的提及,所以我会避开它。
  • 感谢您的回复!我喜欢 iOS 4.3。
  • 我现在注意到,XCode 警告是针对 NSString 的,尽管我使用的是 NSDictionary。奇怪的。再次感谢克里斯!

标签: initwithcontentsoffile invalidargumentexception


【解决方案1】:

正如 Chris 向我指出的那样,NSDictionary 正在按预期工作。

虽然在 XCode 中按住 alt 键单击该方法时,我仍然收到以下消息。 奇怪的是,文档是针对 NSString 而不是 NSDictionary。 应该戴上我的阅读镜,再次感谢克里斯指出答案!

initWithContentsOfFile:
Initializes the receiver, a newly allocated NSString object, by reading data from the file named by path. (Deprecated in iOS 2.0. Use initWithContentsOfFile:encoding:error: or initWithContentsOfFile:usedEncoding:error: instead.)

- (id)initWithContentsOfFile:(NSString *)path
Discussion
Initializes the receiver, a newly allocated NSString object, by reading data from the file named by path. If the contents begin with a byte-order mark (U+FEFF or U+FFFE), interprets the contents as Unicode characters; otherwise interprets the contents as data in the default C string encoding. Returns an initialized object, which might be different from the original receiver, or nil if the file can’t be opened.

Availability
Available in iOS 4.0 and later.
Deprecated in iOS 2.0.
See Also
– initWithContentsOfFile:encoding:error:
– initWithContentsOfFile:usedEncoding:error:
Declared In
NSString.h

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多