2014-09-30 84 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

相關問題