2014-09-30 86 views
1

在iOS模拟器上运行我的程序时,我没有问题。但是在我的iPhone5c上运行时,我遇到了问题。问题是数据加载时会被破坏。这是我的程序源代码。我的代码错在哪里?为什么数据在设备上运行时会被破坏,但不会在模拟器上运行?

概述我的方案:

1.load data from "sample.txt" 
2.log the data 

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:

#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的:

abcdefghijklmnopqrstuvwxyz 

输出:

abcdefghijklmnopqrstuvwxyz 
roj 

预期输出:

abcdefghijklmnopqrstuvwxyz 
+0

你可以试试nsstring * text = [nsstring alloc] initwithdata:self.data]并打印出你将会得到的数据 – iOSdev 2014-09-30 13:35:09

+0

@NarasimhaiahKolli谢谢。但是,我应该使用什么编码? [[NSString分配] initWithData:self.data编码:???] – 2014-09-30 13:46:05

回答

2
NSString* path = [[NSBundle mainBundle] pathForResource:@"sample" ofType:@"txt"]; 
self.data = [NSData dataWithContentsOfFile:path]; 
self.bytePtr = (unsigned char *)[self.data bytes]; 
NSLog(@"%s", self.bytePtr); 

你所访问的数据,就好像它是(使用%s)一个NULL结尾的CString。除非你的文件以\ 0结尾(这看起来没有),否则你的NSLog将会继续读取数据直到找到一个数据。

如果要从文件中读取字符串,请使用stringWithContentsOfURL:encoding:error:

+0

谢谢。我没有注意到问题出现在“%s”中。很好的答案! – 2014-09-30 13:55:56

相关问题