您的位置:首页 > 移动开发 > IOS开发

iOS疯狂讲解之单例模式传值的简单介绍

2015-09-19 11:44 519 查看
#import "SecondViewController.h"
#import "MyHandle.h"
@interface SecondViewController ()

@end

@implementation SecondViewController

- (void)viewDidLoad {
[super viewDidLoad];
NSLog(@"%@", [MyHandle shareHandle].name);
// 修改标题
self.navigationItem.title = [MyHandle shareHandle].name;

}

## 单例模式传值 ##
注意:第一单例是一个类, 创造出来的对象叫单例对象
第二:单例对象一旦被创造出来(开辟空间) 只有到程序结束 才会被释放 就是只初始化一次
第三:单例对象使用类方法创建
第四: 不用程序员管理内存 随程序的关闭而自动释放
第五:方法的命名规范 share开头
## 单例模式传值 ##<pre name="code" class="objc">/ 声明一个属性 用于传值
@property (nonatomic, retain) NSString *name;

+ (MyHandle *)shareHandle;

+ (MyHandle *)shareHandle
{
// 在静态去定义一个指针
static MyHandle *handle = nil;
// 如果这个指针指向的区域为空
if (handle == nil) {
// 就在 堆区开辟空间 创建对象
// 一旦初始化 就不可能为空
// 即 只初始化一次
handle = [[MyHandle alloc] init];
}
return handle;

}

// 下面讲解如何使用单例进行简单的传值重要:单例为什么不能使用自动释放?因为系统方法中 有未知的自动释放池 如果对一个对象进行自动释放的话 该对象可能会进入未知的系统的自动释放池 从而释放 可能会出现内存问题
#import "RootViewController.h"
#import "MyHandle.h"
#import "SecondViewController.h"

@interface RootViewController ()

@property (nonatomic, retain) UITextField *textField;

@end

@implementation RootViewController

- (void)dealloc
{
[_textField release];
[super dealloc];
}
- (void)viewDidLoad {
[super viewDidLoad];
[self addSubViews];

}

- (void)addSubViews
{
self.textField = [[UITextField alloc] initWithFrame:CGRectMake(100, 100, 200, 50)];
self.textField.backgroundColor =[UIColor redColor];
[self.view addSubview:self.textField];
[_textField release];

UIButton *button = [UIButton buttonWithType:(UIButtonTypeCustom)];
button.frame = CGRectMake(100, 200, 100, 20);
button.backgroundColor = [UIColor purpleColor];
[button addTarget:self action:@selector(actionButton:) forControlEvents:(UIControlEventTouchUpInside)];
[self.view addSubview:button];
}

// 实现button的方法
- (void)actionButton:(UIButton *)button
{
// 点击跳转 传值
// 创建一个单例对象  并赋值
[MyHandle shareHandle].name = self.textField.text; // 跟下面的一样
//    MyHandle *handle = [MyHandle shareHandle];
//    handle.name = self.textField.text;

// 跳转第二个页面
SecondViewController *secondVC = [[[SecondViewController alloc] init] autorelease];
[self.navigationController pushViewController:secondVC animated:YES];
}



                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  ios 单例传值