[英]Why a data will be destroyed when running on device but not on simulator?
When running my program on a iOS simulator I didn't have a problem. 在iOS模拟器上运行程序时,我没有遇到任何问题。 But when running on my iPhone5c, I have a problem. 但是在我的iPhone5c上运行时,我遇到了问题。 The problem is data will be destroyed when the data was loaded. 问题是数据在加载时将被破坏。 Here is my program source code. 这是我的程序源代码。 Where my code is wrong? 我的代码哪里有错?
overview of my program: 我的程序概述:
1.load data from "sample.txt"
2.log the data
AppDelegate.h: AppDelegate.h:
#import <UIKit/UIKit.h>
@interface AppDelegate : UIResponder <UIApplicationDelegate>
@property (strong, nonatomic) UIWindow *window;
@property (assign) unsigned char* bytePtr;
@property (strong, nonatomic) NSData* data;
@end
AppDelegate.m: AppDelegate.m:
#import "AppDelegate.h"
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
// Override point for customization after application launch.
self.window.backgroundColor = [UIColor whiteColor];
[self.window makeKeyAndVisible];
[self load];
return YES;
}
- (void) load
{
NSString* path = [[NSBundle mainBundle] pathForResource:@"sample" ofType:@"txt"];
self.data = [NSData dataWithContentsOfFile:path];
self.bytePtr = (unsigned char *)[self.data bytes];
NSLog(@"%s", self.bytePtr);
}
~snip~
sample.txt: sample.txt的:
abcdefghijklmnopqrstuvwxyz
output: 输出:
abcdefghijklmnopqrstuvwxyz
roj
expected output: 预期输出:
abcdefghijklmnopqrstuvwxyz
NSString* path = [[NSBundle mainBundle] pathForResource:@"sample" ofType:@"txt"];
self.data = [NSData dataWithContentsOfFile:path];
self.bytePtr = (unsigned char *)[self.data bytes];
NSLog(@"%s", self.bytePtr);
You're accessing data as though it is a NULL-terminated cstring (using %s
). 您正在访问数据,就好像它是一个以NULL结尾的cstring(使用%s
)。 Unless your file ends in a \\0 (which is doesn't appear to), your NSLog will just keep reading data until it finds one. 除非您的文件以\\ 0结尾(这似乎没有出现),否则NSLog将一直读取数据,直到找到一个为止。
If you want to read a string from a file, using stringWithContentsOfURL:encoding:error:
. 如果要从文件读取字符串,请使用stringWithContentsOfURL:encoding:error:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.