iPhone开发:延时实例化的使用

由于最近玩摄影,认识了很多朋友,也从中真正的认识到分享的重要性。自己做开发这么多年了,没写过几篇文章,趁着2013年,好好的写写。

文章可能有些地方表达的不是很准确或者明白,这也需要一个过程。。。哈~

延时实例化说白了,就是不到最后一秒,它都不会去实例化你需要的东西。例如:

#import <UIKit/UIKit.h>

@interface viewController : UIViewController {

	NSMutableDictionary *postData;
}




#import "viewController.h"

@implementation viewController

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    
    [super viewDidLoad];

    postData = [[NSMutableDictionary alloc] init];
}

代码一开始,就对 postData 进行初始化,其实一开始,我并没有用到。postData 是用于接受用户的操作,如输入一个名字、查找条件等等,然后向服务器提交数据。

也许用户什么也不干就离开了,在一些比较复杂的程序页面中,大量的初始化无疑增加了加载时间,减弱了用户的体验。这时候你可能会想到,我新建一个方法,如:


-(NSMutableDictionary *)postDataInit {

	if (postData == nil) {
		postData = [[NSMutableDictionary alloc] init];
	}

	return postData;
}

上面的方法没错,但objc有一个更加简便方法,生成实例变量,就自动生成了 setter getter方法,这里我只重写 getter方法。


#import <UIKit/UIKit.h>
@interface viewController : UIViewController {

	NSMutableDictionary *postData;
}

@property(nonatomic, retain) NSMutableDictionary *postData;


#import "viewController.h"

@implementation viewController

@synthesize postData = _postData;

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    
    [super viewDidLoad];

}

- (NSMutableDictionary *)postData {

	if (_postData == nil) [[NSMutableDictionary alloc] init];

	return _postData;
}

方法 - (NSMutableDictionary *)postData;  是 @synthesize 生成的getter。当我们使用的时候 [self.postData count],就自动的调用了 - (NSMutableDictionary *)postData,然后假如没用初始化,我们对其进行初始化。已经有了就直接返回。

@synthesize postData = _postData; 

对于此句不懂的同学,可以到  http://moto0421.iteye.com/blog/1577459 进行了解


总结:上面我只是举了一个小例子。在实际写代码中,相信大家会使用很多的开源库、自己写的东西,这些相比例子相信要花费更多的时间的。虽然可能这些对于程序微不足道,但相信养成一个好的习惯总是好的



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值