按下按钮后记录数据(字符*)时显示已损坏

时间:2014-09-28 06:35:05

标签: ios objective-c iphone pointers

我是iphone编程的新手。 问题是当我按下按钮时,数据将被销毁。 我无法找到我的代码错误的地方以及原因。请帮帮我。

这是我的计划概述。

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

感谢。

2 个答案:

答案 0 :(得分:1)

问题是您没有保留NSData对象:

- (void) load
{
    NSString* path = [[NSBundle mainBundle] pathForResource:@"sample" ofType:@"txt"];
    NSData* data = [NSData dataWithContentsOfFile:path];   // here
    self.bytePtr = (unsigned char *)[data bytes];
    NSLog(@"%s", self.bytePtr);
}

一旦该方法返回,NSData对象将被销毁,因此self.bytePtr指向的缓冲区不再有效。

要解决此问题,请将self.bytePtr更改为NSData对象并将其存储。

答案 1 :(得分:0)

首先,为了接收您的alertView:clickedButtonAtIndex:方法调用,您需要将UIAlertView委托设置为自己。

[alertView setDelegate:self] // make sure you set UIAlertViewDelegate protocol on the method owner

否则,您应该使用NSString初始化的initWithData:encoding:对象。

相关问题