When running my program on a iOS simulator I didn't have a problem. But when running on my iPhone5c, I have a problem. 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:
#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
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
). Unless your file ends in a \0 (which is doesn't appear to), your NSLog will just keep reading data until it finds one.
If you want to read a string from a file, using stringWithContentsOfURL:encoding:error:
.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments