iPhone内存管理,EXC_BAD_ACCESS之间的NSString视图

时间:2011-10-13 18:37:03

标签: iphone memory-management nsstring views

我在内存管理方面遇到了一些问题,我认为我的问题是分配和对象发布。我想将NSString(userID)值分配给其他视图中的另一个NSString(user_id)。

MainViewController.h

#import "OnlineCheckViewController.h"

@interface MainViewController : UIViewController
{
    NSString *userID;
}
@end

MainViewController.m

#import "MainViewController.h"

- (IBAction)OnlineCheck:(id)sender
{
    OnlineCheckViewController *controller = [[OnlineCheckViewController alloc] initWithNibName:@"OnlineCheckViewController" bundle:nil];
    controller.delegate = self;

    controller.user_id = userID;

    controller.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
    [self presentModalViewController:controller animated:YES];

    [controller release];
}
- (void)viewDidUnload
{
    userID = nil;
    [super viewDidUnload];
}

- (void)dealloc
{
    [userID release];
    [super dealloc];
}

OnlineCheckViewController.h

#import <UIKit/UIKit.h>
#import "OnlineCheckResultsViewController.h"

@protocol OnlineCheckViewControllerDelegate;

@interface OnlineCheckViewController : UIViewController 
     <OnlineCheckResultsViewControllerDelegate>
{
    NSString *user_id;
}

@property (nonatomic, assign) id <OnlineCheckViewControllerDelegate> delegate;
@property (nonatomic, retain) NSString *user_id;

@end

OnlineCheckViewController.m

#import "OnlineCheckViewController.h"

@synthesize user_id;
@synthesize delegate=_delegate;

- (void)dealloc
{
    [user_id release];
    [super dealloc];
}
- (void)viewDidUnload
{
    [self setUser_id:nil];
    [super viewDidUnload];
}

谢谢!

3 个答案:

答案 0 :(得分:0)

@interface MainViewController : UIViewController
{
    NSString *userID;
}

我打赌这是你的问题。请注意,在创建属性“user_id”时,请指定“retain”。保留确保处理器在您告知之前不会释放字符串。

NSString自动设置为自动释放。如果您打算将值保存在非属性NSString(userID)中,则需要调用[userID retain];在设置它的值之后。

我猜你从未保留过userID,当你尝试将user_id设置为它时,它更可能调用错误,它会抛出错误,因为你在dealloc中释放它。

答案 1 :(得分:0)

试试此代码

- (IBAction)OnlineCheck:(id)sender
{
    OnlineCheckViewController *controller = [[OnlineCheckViewController alloc] initWithNibName:@"OnlineCheckViewController" bundle:nil];
    controller.delegate = self;

    controller.user_id = userID;
    [controller.user_id retain];
    controller.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
    [self presentModalViewController:controller animated:YES];

    [controller release];
}

我认为这可以解决你的问题...

答案 2 :(得分:0)

感谢您的所有答案。

我已经解决了这个问题。

MainViewController.h

我添加了userID IBOutlet

@property (nonatomic, retain) IBOutlet NSString *userID;

MainViewController.m

@synthesize userID;

- (IBAction)OnlineCheck:(id)sender
{
controller.user_id = self.userID;
}

- (void)viewDidUnload
{
self.userID = nil;
}

- (void)dealloc
{
[userID release];
}

OnlineCheckViewController.h

更改为分配

@property (nonatomic, assign) NSString *user_id;

OnlineCheckViewController.m

- (void)dealloc
{
// removed
// [user_id release];
}

- (void)viewDidUnload
{
// removed
// [self setUser_id:nil];
}