gpt4 book ai didi

ios - 为什么在设备上运行时数据会被破坏,而在模拟器上不会?

转载 作者:行者123 更新时间:2023-11-29 10:37:37 28 4
gpt4 key购买 nike

在 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~

示例.txt:

abcdefghijklmnopqrstuvwxyz

输出:

abcdefghijklmnopqrstuvwxyz
roj

预期输出:

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);

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

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

关于ios - 为什么在设备上运行时数据会被破坏,而在模拟器上不会?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26122152/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com