1.模仿原生的写法,可以得到一些启示:
Mutable 的写法:
(1). 用const :
typedef struct CGPath *CGMutablePathRef;
typedef const struct CGPath *CGPathRef;
(2). 用ReadOnly :
比如:NSRequest 之所以不可变就是因为其中的NSURL的属性是ReadOnly,而NSMutableRequest可变就是没有这个属性关键字:
NSRequest
@property (nullable, readonly, copy) NSURL *URL;
NSMutableRequest
@property (nullable, copy) NSURL *URL;
所以属性也可以继承的哦,因为属性是相当于一getset方法来用的。
2.用宏来描述系统版本:
// iOS Version check for iOS 8.0.0
#define SYSTEM_VERSION_IS_8_0_X ([[[UIDevice currentDevice] systemVersion] hasPrefix:@"8.0"])
3.布尔值,多炫酷:
- (void) Togglemap
{
mapView.layer.hidden = (mapView.layer.hidden == NO)?YES:NO;
}
4.可以直接调按钮的点击事件!!
[self buttonClicked:self.testButton];
像这样传个参过去即可!!
这个不懂的话就是没理解iOS 的target action啦。管你是什么事件,随便调!!
5.判空啊 判空啊!!
void safefree(void **pp)
{
if (pp != NULL) { /* safety check */
free(*pp); /* deallocate chunk, note that free(NULL) is valid */
*pp = NULL; /* reset original pointer */
}
}
int f(int i)
{
char *p = NULL, *p2;
p = (char *)malloc(1000); /* get a chunk */
p2 = p; /* copy the pointer */
/* use the chunk here */
safefree(&p); /* safety freeing; does not affect p2 variable */
safefree(&p); /* this second call won't fail */
char c = *p2; /* p2 is still a dangling pointer, so this is undefined behavior. */
}
同理的:
if (self.containerView.superview) {
[self.containerView removeFromSuperview];
}
这些都是好习惯啊!
6. 分段宏,优雅,可读!
// dev idfa idfv 存keychain的处理
#define SY_DEVICE_INFO_KEY @"SYDeviceInfoKey"
#define SY_DEVICE_INFO_SERVICE @"SYDeviceInfoService"
7. 分段宏,优雅,可读!
@property (nonatomic, strong) id currentTextField; // 标记键盘.
#pragma mark - UITextFieldDelegate
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
_currentTextField = textField;
}
[_currentTextField resignFirstResponder];
理解指针的人都喜欢这么用!
8.判空并不是一定是nil null 啥的,还有这样的判空:
NSString *framework = [[NSBundle mainBundle] pathForResource:@"Frameworks/xxxx.framework"
ofType:nil];
if (![[NSFileManager defaultManager] fileExistsAtPath:framework
isDirectory:nil]){
NSLog(@"Error: dynamic framework is not existed!");
}
9.初始化可变数组的一个方式
NSMutableArray *objectsArray = [@[] mutableCopy];
10.研究iOS的一些方法
可以用KVC这种超级灵敏的方式,例如,设置了KVC之后,当进入视图,会发现,马上响应,从而知道iOS是初始配置这些属性
[scrollView addObserver:self forKeyPath:@"contentOffset" options:NSKeyValueObservingOptionNew context:nil];
[scrollView addObserver:self forKeyPath:@"contentInset" options:NSKeyValueObservingOptionNew context:nil];
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{
NSLog(@"observeValueForKeyPath KeyPath : %@", keyPath);
}
即初始状态设的值CGPointZero也会马上响应KVO/KVC.