Method Swizzling ,它通过重新映射方法对应的实现来达到“偷天换日”的目的。跟消息转发相比,Method Swizzling 的做法更为隐蔽,甚至有些冒险,也增大了debug的难度。
-(void)viewWillAppear:(BOOL)animated{
[super viewWillAppear:animated];
NSLog(@"viewWillAppear");
}
-(void)sxChangeViewWillAppear:(BOOL)animated{
NSLog(@"sxChangeViewWillAppear");
[self sxChangeViewWillAppear:animated];
}
+(void)load{
SEL originalSel = @selector(viewWillAppear:);
SEL changeSel = @selector(sxChangeViewWillAppear:);
Method originalMethod = class_getInstanceMethod(self, originalSel);
Method changeMethod = class_getInstanceMethod(self, changeSel);
if (class_addMethod(self, originalSel, method_getImplementation(changeMethod), method_getTypeEncoding(changeMethod))) {
class_replaceMethod(self, changeSel, method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod));
}else{
method_exchangeImplementations(originalMethod, changeMethod);
}
}
//获取某个类所有成员变量
id LenderClass = objc_getClass("Lender");
unsigned int outCount, i;
objc_property_t *properties = class_copyPropertyList(LenderClass, &outCount);
for (i = 0; i < outCount; i++) {
objc_property_t property = properties[i];
fprintf(stdout, "%s %s\n", property_getName(property), property_getAttributes(property));
}
崩溃日志:
有几种方法可以从设备上获取崩溃日志。
设备与电脑上的iTunes Store同步后,会将崩溃日志保存在电脑上。根据电脑操作系统的不同,崩溃日志将保存在以下位置:
Mac OS X:~/Library/Logs/CrashReporter/MobileDevice/
Windows XP: C:Documents and Settings<USERNAME>Application DataApple ComputerLogsCrashReporterMobileDevice<DEVICE_NAME>
Windows Vista or 7: C:Users<USERNAME>AppDataRoamingApple ComputerLogsCrashReporterMobileDevice<DEVICE_NAME>
//app 评分
NSString *strUrl = @"itms-apps://itunes.apple.com/WebObjects/MZStore.woa/wa/viewContentsUserReviews?type=Purple+Software&id=app_id;
NSURL *url = [NSURL URLWithString:strUrl];
[[UIApplication sharedApplication] openURL:url];
iOS中的round/ceil/floorf函数略解
round:如果参数是小数,则求本身的四舍五入。
ceil:如果参数是小数,则求最小的整数但不小于本身.
floor:如果参数是小数,则求最大的整数但不大于本身.
//查看静态库 支持哪些系统
sudo lipo -info libPushSDK.a
终端查BUG
sudo malloc_history 50127 0x6d564f0
// 50127 为活动监视器中应用的pid 进程号
xcode 控制台输入语法
po
po [[self view] recursiveDescription]
//tableView 滑动关闭键盘
self.tableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeInteractive;
//单个文件的大小
- (long long) fileSizeAtPath:(NSString*) filePath{
NSFileManager* manager = [NSFileManager defaultManager];
if ([manager fileExistsAtPath:filePath]){
return [[manager attributesOfItemAtPath:filePath error:nil] fileSize];
}
return 0;
}
//关于NSLog 在DEBug 环境打印到控制台,Release 环境不做处理
#ifdef DEBUG
//unterminated conditional directive
#define DMLog(...) NSLog(@"%s %@", __PRETTY_FUNCTION__, [NSString stringWithFormat:__VA_ARGS__])
#else
#define DMLog(...) do { } while (0)
#ifndef __OPTIMIZE__
# define NSLog(...) NSLog(__VA_ARGS__)
#else
# define NSLog(...) {}
#endif
//collectionView 数据不够里也能滑动
self.collectionView.alwaysBounceVertical = YES;
self.collectionView.alwaysBounceHorizontal = YES;
//ios6 与ios7 屏暮0,0点的调整
self.edgesForExtendedLayout = UIRectEdgeNone;
[self.navigationController.navigationBar setTranslucent:NO];
//沙盒文件相关
NSString * path = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/Medias"];
BOOL isExists;
if (![[NSFileManager defaultManager] fileExistsAtPath:path isDirectory:&isExists]&&!isExists) {
NSError * error;
//创建文件夹
[[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:&error];
if (error) {
NSLog(@"创建错误");
}else{
NSLog(@"创建成功");
}
}else{
NSLog(@"路径已存在");
}
[[NSFileManager defaultManager] createDirectoryAtPath:mediaPath withIntermediateDirectories:YES attributes:nil error:nil];
1,path:所要创建文件夹的路径。
2,createIntermediates:所要创建的目录的父目录等相关的目录可能并不存在。如果想要把相关目录一起创建了,就把这个参数设成YES,否则设成NO。设成NO的话,假如父目录不存在,函数就会失败,函数返回值就是NO。
3,attributes:这个参数就是创建目录时的一些选项设置,所有可以配置项的键可以在这里找到。一般设成nil就行了。采用默认的设置。
4,error:函数执行错误时返回的错误对象,注意应返回的是一个地址;
在ios开发的过程中,有可能这里应用在iphone和ipad上都要使用,但是怎么判断当前设备是iphone还是ipad呢,在这里提供一种方法来判断这个设备是什么设备,具体代码如下
NSString *nibTitle = @"PadContent"; //默认是ipad if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) { //如果当前设备是iphone 就改为iphone的nib文件 nibTitle = @"PhoneContent"; } [[NSBundle mainBundle] loadNibNamed:nibTitle owner:self options:nil];//加载nib |
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions
{
self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
// Override point for customization after application launch.
if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
self.viewController = [[[ViewController alloc] initWithNibName:@"ViewController_iPhone"bundle:nil] autorelease];
} else {
self.viewController = [[[ViewController alloc] initWithNibName:@"ViewController_iPad"bundle:nil] autorelease];
}
self.window.rootViewController = self.viewController;
[self.window makeKeyAndVisible];
return YES;
}
//取XIB
//self.sxView = [[[UINib nibWithNibName:@"SXView" bundle:nil] instantiateWithOwner:nil options:nil] lastObject];
self.sxView= [[[NSBundle mainBundle] loadNibNamed:@"SXView" owner:self options:nil] lastObject];
设备应用尺寸
float scale = [[UIScreenmainScreen] scale];//得到设备的分辨率
scale = 1; 的时候是代表当前设备是320*480的分辨率(就是iphone4之前的设备)
scale = 2; 的时候是代表分辨率为640*960的分辨率
//IOS设备适配
[[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone
app尺寸,去掉状态栏
CGRect r = [ UIScreen mainScreen ].applicationFrame;
r=0,20,320,460
屏幕尺寸
CGRect rx = [ UIScreen mainScreen ].bounds;
r=0,0,320,480
状态栏尺寸
CGRect rect; rect = [[UIApplication sharedApplication] statusBarFrame];
iphone中获取屏幕分辨率的方法
CGRect rect = [[UIScreen mainScreen] bounds];
CGSize size = rect.size;
CGFloat width = size.width;
CGFloat height = size.height;
另外,设计UI的时候,注意用户最小的触控面积。有2种说法
44*44 好像是来自sdk
64*64 来自standford讲义
字符串
str= [str stringByReplacingOccurrencesOfString:@"sa" withString:@"ABC" options:NSLiteralSearch range:NSMakeRange(0,20)];// 在0-20的范围内查找
//NSLiteralSearch-->区分大小
//NSCaseInsensitiveSearch--》不区分大小
//获取字符串的文本size
NSString * str;
str sizeWithFont:(UIFont *) constrainedToSize:(CGSize) lineBreakMode:(NSLineBreakMode)
//获取类名—返回字符串
NSStringFromClass(self.class);
关于手势
// 当某个手势失效后,再执行另一个手势
[scrollViewTap requireGestureRecognizerToFail:tap];
//关于用户事件 —imageView的userInteractionEnabled默认是NO,如果需要添加TOUCH或手势按钮,需设置为YES
// 应用程序完全停止接收触摸事件消息;第二个方法恢复接收消息。
[[UIApplication sharedApplication] beginIgnoringInteractionEvents];
[[UIApplication sharedApplication] endIgnoringInteractionEvents];
关闭触摸事件的递交。 缺省情况下,视图接收触摸事件,但是你可以设置它的userInteractionEnabled 属性为NO来关闭事件提交。视图在隐藏或透明时也不会接收事件。
限制事件递交给单个视图。 缺省情况下,一个视图的exclusiveTouch 属性被设置为NO, 这意味着这个视图不会阻塞该窗口中的其它视图接收触摸事件。如果你把这个属性设置为YES,你标记这个视图以便,当它跟踪触摸时,它是当前窗口中唯一可以跟踪触摸的视图。窗口中的其它视图将不能接收触摸事件。不过,被标记为“exclusive touch”的视图不能接收相同窗口中其它视图相关的触摸事件。如果一个手指接触了一个exclusive-touch 视图, 那么这个触摸事件仅在该视图是当前窗口中唯一跟踪这个手指的视图时才会被递交出去。如果一个手指触摸了一个non-exclusive 视图, 那么这个触摸事件仅在没有其它手指 被一个exclusive-touch 视图跟踪时才会被递交出去。
限制事件递交给子视图。一个自定义UIView 类可以重写hitTest:withEvent: 来限制多点触摸事件递交给它的子视图。
检测数组数据中是否包含指定的对象元素
- (BOOL)containsObject:(id)anObject;
//image 加深
UIImage * image =[[UIImage imageNamed:@"exCell.png"]resizableImageWithCapInsets:UIEdgeInsetsMake(20, 20, 20, 20)];
//显示当前tableView正的显示的cell
[self.tableView indexPathsForVisibleRows];
//视图跳转
self.presentingViewController—》表示 跳转后 ,上一个视图控制器
self.presentedViewController—》表示 跳转后显示的视图控制器
//设置视图跳转的动画风格
ViewController.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
//关于sd加载图片的监听
if (NSClassFromString(@"SDNetworkActivityIndicator"))
{
id activityIndicator = [NSClassFromString(@"SDNetworkActivityIndicator") performSelector:NSSelectorFromString(@"sharedActivityIndicator")];
[[NSNotificationCenter defaultCenter] addObserver:activityIndicator
selector:NSSelectorFromString(@"startActivity")
name:SDWebImageDownloadStartNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:activityIndicator
selector:NSSelectorFromString(@"stopActivity")
name:SDWebImageDownloadStopNotification object:nil];
}
//获取当前屏幕显示的viewController
-(UIViewController *)getCurrentRootViewController {
UIViewController *result;
UIWindow *topWindow = [[UIApplication sharedApplication] keyWindow];
if (topWindow.windowLevel != UIWindowLevelNormal)
{
NSArray *windows = [[UIApplication sharedApplication] windows];
for(topWindow in windows)
{
if (topWindow.windowLevel == UIWindowLevelNormal)
break;
}
}
UIView *rootView = [[topWindow subviews] objectAtIndex:0];
id nextResponder = [rootView nextResponder];
if ([nextResponder isKindOfClass:[UIViewController class]])
result = nextResponder;
else if ([topWindow respondsToSelector:@selector(rootViewController)] && topWindow.rootViewController != nil)
result = topWindow.rootViewController;
else
NSAssert(NO, @"ShareKit: Could not find a root view controller. You can assign one manually by calling [[SHK currentHelper] setRootViewController:YOURROOTVIEWCONTROLLER].");
return result;
}
//ios 沙盒路径
NSHomeDirectory();
NSLog(@"--temp:%@",NSTemporaryDirectory());
NSString *cacheDirectory = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSLog(@"%@--%@",cacheDirectory, NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES));
//获取已下载的文件大小
- (unsigned long long)fileSizeForPath:(NSString *)path { //path为绝对路径
signed long long fileSize = 0;
NSFileManager *fileManager = [NSFileManager new]; // default is not thread safe
if ([fileManager fileExistsAtPath:path]) {
NSError *error = nil;
NSDictionary *fileDict = [fileManager attributesOfItemAtPath:path error:&error];
if (!error && fileDict) {
fileSize = [fileDict fileSize];
}
}
return fileSize;
}
//悬浮效果
self.backgroundColor = [UIColor clearColor];
self.contentView.backgroundColor = [UIColor whiteColor];
self.contentView.layer.shadowOpacity = 0.2f;
self.contentView.layer.shadowOffset = CGSizeMake(0, 0);
self.contentView.layer.cornerRadius = 4;
//视图抖动效果
- (void)shakeView:(UIView *)viewToShake
{
CGFloat t = 6.0;
CGFloat u = 2.0;
CGAffineTransform translateRight = CGAffineTransformTranslate(CGAffineTransformIdentity, t, u);
CGAffineTransform translateLeft = CGAffineTransformTranslate(CGAffineTransformIdentity, -t, -u);
viewToShake.transform = translateLeft;
__block UIView * shakeView = viewToShake;
[UIView animateWithDuration:0.07 delay:0.0 options:UIViewAnimationOptionAutoreverse|UIViewAnimationOptionRepeat animations:^{
[UIView setAnimationRepeatCount:3.0];
shakeView.transform = translateRight;
} completion:^(BOOL finished) {
if (finished) {
[UIView animateWithDuration:0.05 delay:0.0 options:UIViewAnimationOptionBeginFromCurrentState animations:^{
shakeView.transform = CGAffineTransformIdentity;
} completion:NULL];
}
}];
}
1.url编码
ios中http请求遇到汉字的时候,需要转化成UTF-8,用到的方法是:
NSString * encodingString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
2.url解码
请求后,返回的数据,如何显示的是这样的格式:%3A%2F%2F,此时需要我们进行UTF-8解码,用到的方法是:
NSString *str = [model.album_name stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];