为什么在设备上运行而不是在模拟器上运行会破坏数据?

时间:2014-09-30 13:31:10

标签: ios objective-c iphone xcode

在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

1 个答案:

答案 0 :(得分: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);

您正在访问数据,就好像它是以NULL结尾的cstring(使用%s)。除非您的文件以\ 0结尾(看起来不是这样),否则您的NSLog将继续读取数据,直到找到它为止。

如果您想使用stringWithContentsOfURL:encoding:error:从文件中读取字符串。