我對iphone編程很新手。 問題是當我按下按鈕時,數據將被銷燬。 我找不到我的代碼錯在哪裏以及爲什麼。請幫幫我。按下按鈕後,數據(char *)在登錄後出現損壞
這是我的程序概述。
1. load text data from "sample.txt"
2. log the data
3. When I push a button, it logs the data again.
AppDelegate.h
#import <UIKit/UIKit.h>
@interface AppDelegate : UIResponder <UIApplicationDelegate>
@property (strong, nonatomic) UIWindow *window;
@property (strong, nonatomic) UIButton *myButton1;
@property (assign) unsigned char* bytePtr;
@end
AppDelegate.m:
~snip~
- (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.myButton1 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[self.myButton1 setFrame:CGRectMake(0, 0, 100 ,100)];
[self.myButton1 addTarget:self action:@selector(button1DidPushed) forControlEvents:UIControlEventTouchUpInside];
[self.myButton1 setTitle:@"push" forState:UIControlStateNormal];
[self.window addSubview:self.myButton1];
[self load];
return YES;
}
- (void) load
{
NSString* path = [[NSBundle mainBundle] pathForResource:@"sample" ofType:@"txt"];
NSData* data = [NSData dataWithContentsOfFile:path];
self.bytePtr = (unsigned char *)[data bytes];
NSLog(@"%s", self.bytePtr);
}
- (void)button1DidPushed
{
UIAlertView *alerView = [[UIAlertView alloc] initWithTitle:@"Enter something..." message:@"" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"OK", nil];
alerView.alertViewStyle = UIAlertViewStylePlainTextInput;
[alerView show];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
NSString *title = [alertView buttonTitleAtIndex:buttonIndex];
if([title isEqualToString:@"OK"])
{
}
NSLog(@"%s", self.bytePtr);
}
~snip~
sample.txt的:
abcdefghijklmnopqrstuvwxyz
輸出:
abcdefghijklmnopqrstuvwxyz
<----- When I push the button the mark similar to "?" will appear on output window.(I couldn't show it here(It's probabily ascii code 2(STX))) That is why I think the data is destroyed.
環境:
xcode 6.0.1
感謝。
如果你希望你的'bytePtr'存儲數據,它不會。當數據超出範圍時,該指針的值將毫無意義。你應該閱讀關於指針/通用C編程。 – sapi 2014-09-28 06:38:37