Cocoa - problem with this code using NSBundle

亡梦爱人 提交于 2019-12-06 16:17:54

问题


It was suggested that I use this line of code to call an image from my resources folder/project bundle. I also see it being used exactly like this on many different website tutorials.

NSBundle *mb=[NSBundle mainBundle];


NSString *fp=[mb pathForResource:@"topimage" ofType:@"PNG"];


NSImage *image=[NSImage initWithContentsOfFile:fp];

HOWEVER, I am receiving the following warning:

NSImage may not respond to +initWithContentsOfFile+

The documentation for NSImage shows that initWithContentsOfFile is in fact a method that should work. What might I be missing here?


回答1:


You're missing an +alloc

NSImage* image = [[NSImage alloc] initWithContentsOfFile:fp];

You can also use +imageNamed:, which fetches images from your main bundle.

NSImage* image = [NSImage imageNamed:@"topImage.png"];



回答2:


initWithContentsOfFile: is an instance method, but you're sending that message to the NSImage class. You need to send it to an instance—specifically, a freshly-allocated instance.

That's where alloc comes in. It's a class method that allocates an instance, which you then immediately send the init… message (as Darren showed).

Don't forget to release the instance when you're done with it. I generally autorelease the instance immediately after initing it; then, Cocoa will release the instance for me at an appropriate time. See the Memory Management Programming Guide for Cocoa for more information.



来源:https://stackoverflow.com/questions/1659407/cocoa-problem-with-this-code-using-nsbundle

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