今天在看例程时遇到了下面的代码,首先第一行就不懂了。
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
//初始化
NSData *data = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"data" ofType:@"json"]];
// NSString *result = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
// NSLog(@"%@", result);
model = [IoTProcessModel startWithAppID:IOT_APPKEY appSecret:IOT_APP_SECRET product:IOT_PRODUCT productJson:data];
model.delegate = self;
后来查了NSData 是一个object,用来存放文件内容的,但是这个文件又是怎么指定的呢? NSBundle又是干嘛的呢。
然后继续查。
终于知道了,原来apple把跟app相关的一些文件,数据结构等都存放到一个子目录中,然后用一个object来维护这个子目录,这个object就是bundle,当我们在某个app内部调用NSBundle mainBundle时就获取了一个该app的bundle实例,那么这个时候,就可以通过文件名来获取指定的文件内容 pathForResource后面跟的字符串就是文件名,ofType指的是扩展名,所以例子里面的意思是先获取.data.json这个文件的路径,然后把文件的内容搞到NSData *data指向对象中。再后面的就不管了,重点只是刚才描述的那一段。
看下图,在Resource里面果然有一个名为data.json的文件。
下面附上apple原文对NSBundle的解释。
参考链接为:https://developer.apple.com/reference/foundation/nsbundle?language=objc
NSBundle
An NSBundle
object helps you access the code and resources in a bundle directory on disk. Apple uses bundles to represent apps, frameworks, plug-ins, and many other specific types of content. Bundles organize their contained resources into well-defined subdirectories, and bundle structures vary depending on the platform and the type of the bundle. By using a bundle object, you do not have to know the structure of a bundle to access its resources. The bundle object provides a single interface for locating items, taking into account the bundle structure, user preferences, available localizations, and other relevant factors.