用途:

NSInvocation的作用和performSelector:withObject:的作用是一样的:用于iOS编程中调用某个对象的消息。

performSelector:withObject:调用一些参数较少的消息是比较方便的,但是对于参数个数大于2的消息,使用NSInvocation还是比较方便的。

因为NSInvocation是静态的呈现Objective-C的消息,也就是说,它把一个行动变成了一个对象。NSInvocation对象用于对象之间和应用程序之间存储和转发消息,主要通过NSTimer对象和分布式对象系统来完成。

代码:

//
// NSInvocation+Improved.h
// InvocationDemo
//
// Created by 李振杰 on 13-12-11.
// Copyright (c) 2013年 swplzj. All rights reserved.
// #import <Foundation/Foundation.h> @interface NSInvocation (Improved) + (NSInvocation *)invocationWithTarget:(id)_target andSelector:(SEL)_selector;
+ (NSInvocation *)invocationWithTarget:(id)_target andSelector:(SEL)_selector andArguments:(void *)_addressOfFirstArgument, ...;
- (void)invokeOnMainThreadWaitUntilDone:(BOOL)wait; @end
//
// NSInvocation+Improved.m
// InvocationDemo
//
// Created by 李振杰 on 13-12-11.
// Copyright (c) 2013年 swplzj. All rights reserved.
// #import "NSInvocation+Improved.h" @implementation NSInvocation (Improved) + (NSInvocation *)invocationWithTarget:(id)_target andSelector:(SEL)_selector
{
//方法签名类
//需要给定一个方法,用于必须创建一个NSInvocation对象的情况下,例如在消息的转发。
NSMethodSignature *methodSig = [_target methodSignatureForSelector:_selector];
//根据方法签名类来创建一个NSInvocation
/*
一个NSInvocation是静态的呈现Objective-C的消息,也就是说,它是一个行动变成了一个对象。 NSInvocation对象用于对象之间和在应用程序之间存储和转发消息,主要通过NSTimer对象和分布式对象系统来完成。
*/
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:methodSig];
[invocation setTarget:_target];
[invocation setSelector:_selector];
return invocation;
} + (NSInvocation *)invocationWithTarget:(id)_target andSelector:(SEL)_selector andArguments:(void *)_addressOfFirstArgument, ...
{
NSMethodSignature *methodSig = [_target methodSignatureForSelector:_selector];
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:methodSig];
[invocation setTarget:_target];
[invocation setSelector:_selector];
//获得签名类对象的参数个数
unsigned int numArgs = [methodSig numberOfArguments];
//PS:atIndex的下标必须从2开始。原因:0 1 两个参数已经被target 和selector占用
if (2 < numArgs) {
/*
VA_LIST 是在C语言中解决变参问题的一组宏,所在头文件:#include <stdarg.h>
VA_START宏,获取可变参数列表的第一个参数的地址(ap是类型为va_list的指针,v是可变参数最左边的参数)
VA_ARG宏,获取可变参数的当前参数,返回指定类型并将指针指向下一参数(t参数描述了当前参数的类型)
VA_END宏,清空va_list可变参数列表
*/ /*
用法:
(1)首先在函数里定义一具VA_LIST型的变量,这个变量是指向参数的指针;
(2)然后用VA_START宏初始化刚定义的VA_LIST变量;
(3)然后用VA_ARG返回可变的参数,VA_ARG的第二个参数是你要返回的参数的类型(如果函数有多个可变参数的,依次调用VA_ARG获取各个参数);
(4)最后用VA_END宏结束可变参数的获取。
*/
va_list varargs; va_start(varargs, _addressOfFirstArgument);
[invocation setArgument:_addressOfFirstArgument atIndex:2]; for (int argIndex = 3; argIndex < numArgs; argIndex++) {
void *argp = va_arg(varargs, void *);
[invocation setArgument:argp atIndex:argIndex];
} va_end(varargs);
}
return invocation;
} - (void)invokeOnMainThreadWaitUntilDone:(BOOL)wait
{
[self performSelectorOnMainThread:@selector(invoke) withObject:nil waitUntilDone:wait];
} @end

自定义类:

//
// SomeClass.h
// InvocationDemo
//
// Created by 李振杰 on 13-12-11.
// Copyright (c) 2013年 swplzj. All rights reserved.
// #import <Foundation/Foundation.h> @interface SomeClass : NSObject - (void)commonOperation;
- (void)improvedOperation;
- (void)fireTimer:(NSDictionary *)user andDate:(NSDate *)startTime; @end
//
// SomeClass.m
// InvocationDemo
//
// Created by 李振杰 on 13-12-11.
// Copyright (c) 2013年 swplzj. All rights reserved.
// #import "SomeClass.h"
#import "NSInvocation+Improved.h" @implementation SomeClass - (void)commonOperation
{
NSDate *date = [NSDate date];
NSDictionary *user = [NSDictionary dictionaryWithObjectsAndKeys:@"value1", @"key1", nil];
SEL method = @selector(fireTimer:andDate:);
NSMethodSignature *signature = [[self class] instanceMethodSignatureForSelector:method];
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:signature];
[invocation setTarget:self];
[invocation setSelector:method];
[invocation setArgument:&user atIndex:2];
[invocation setArgument:&date atIndex:3];
// [NSTimer scheduledTimerWithTimeInterval:0.1 invocation:invocation repeats:YES];
[invocation invoke];
} - (void)improvedOperation
{
//1.创建一个没有参数的NSInvocation
// SEL selector = @selector(fireTimer:andDate:);
// NSInvocation *invocation = [NSInvocation invocationWithTarget:self andSelector:selector]; //2.创建带有两个参数的NSInvocation
NSDate *date = [NSDate date];
NSDictionary *user = [NSDictionary dictionaryWithObjectsAndKeys:@"value1", @"key1", nil];
NSInvocation *invocation = [NSInvocation invocationWithTarget:self andSelector:@selector(fireTimer:andDate:) andArguments:&user, &date];
[invocation invoke];
} - (void)fireTimer:(NSDictionary *)user andDate:(NSDate *)startTime
{
/*
sleep 与 sleepForTimeInterval的区别
sleep直接让线程停掉,sleepForTimeInterval是让runLoop停掉。比如说,你有2个APP,分别是A和B,A启动B,然后去取B的进程号,如果你用sleep等B启动再去取,你会发现取不到,因为你只是把代码加到runloop里面去,而runloop并没有执行到这句,sleep就直接让系统停在那里,所以取不到,而后者就没问题,因为它是让runloop执行到这句的时候停1s
*/ [NSThread sleepForTimeInterval:2];
NSTimeInterval timeInterval = -1 * [startTime timeIntervalSinceNow];
NSString *timeStr = [NSString stringWithFormat:@"%.2f", timeInterval];
NSLog(@"fireTime: %@", timeStr);
} @end

调用SomeClass:

//
// AppDelegate.m
// InvocationDemo
//
// Created by 李振杰 on 13-12-11.
// Copyright (c) 2013年 swplzj. All rights reserved.
// #import "AppDelegate.h"
#import "SomeClass.h" @implementation AppDelegate - (void)dealloc
{
[_window release];
[super dealloc];
} - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
// Override point for customization after application launch. SomeClass *some = [[SomeClass alloc] init];
[some commonOperation];
[some improvedOperation];
[some release]; self.window.backgroundColor = [UIColor whiteColor];
[self.window makeKeyAndVisible];
return YES;
} @end

Demo源码:

此Demo源码的下载链接。

iOS NSInvocation的学习的更多相关文章

  1. IOS NSInvocation用法简介

    IOS NSInvocation用法简介 2012-10-25 19:59 来源:博客园 作者:csj007523 字号:T|T [摘要]在 iOS中可以直接调用某个对象的消息方式有两种,其中一种就是 ...

  2. iOS开发如何学习前端(2)

    iOS开发如何学习前端(2) 上一篇成果如下. 实现的效果如下. 实现了一个横放的<ul>,也既iOS中的UITableView. 实现了当鼠标移动到列表中的某一个<li>,也 ...

  3. iOS开发如何学习前端(1)

    iOS开发如何学习前端(1) 我为何学前端?因为无聊. 概念 前端大概三大块. HTML CSS JavaScript 基本上每个概念在iOS中都有对应的.HTML请想象成只能拉Autolayout或 ...

  4. 移动开发iOS&Android对比学习--异步处理

    在移动开发里很多时候需要用到异步处理.Android的主线程如果等待超过一定时间的时候直接出现ANR(对不熟悉Android的朋友这里需要解释一下什么叫ANR.ANR就是Application Not ...

  5. 关于iOS开发的学习

    关于iOS开发的学习,打个比方就像把汽车分解:    最底层的原料有塑料,钢铁    再用这些底层的东西造出来发动机,座椅    最后再加上写螺丝,胶水等,把汽车就拼起来了 iOS基本都是英文的资料, ...

  6. IOS科研IOS开发笔记学习基础知识

    这篇文章是我的IOS学习笔记,他们是知识的基础,在这里,根据记录的查询后的条款. 1,UIScrollView能完毕滚动的功能. 示比例如以下: UIScrollView *tableScrollVi ...

  7. iOS核心动画学习整理

    最近利用业余时间终于把iOS核心动画高级技巧(https://zsisme.gitbooks.io/ios-/content/chapter1/the-layer-tree.html)看完,对应其中一 ...

  8. iOS CoreData技术学习资源汇总

    一.CoreData学习指引 1. 苹果官方:Core Data Programming Guide 什么是CoreData? 创建托管对象模型 初始化Core Data堆栈 提取对象 创建和修改自定 ...

  9. IOS内存管理学习笔记

    内存管理作为iOS中非常重要的部分,每一个iOS开发者都应该深入了解iOS内存管理,最近在学习iOS中整理出了一些知识点,先从MRC开始说起. 1.当一个对象在创建之后它的引用计数器为1,当调用这个对 ...

随机推荐

  1. cmd连接mysql连接:mysql-h主机地址-u用户名-p用户密码(注:u与root可以不用加)

    MySQL导入导出命令1.导出整个数据库 mysqldump -u 用户名 -p 数据库名 > 导出的文件名 mysqldump -u wcnc -p smgp_apps_wcnc >wc ...

  2. Animation动画(一)

    Android的animation由四种类型组成:alpha(渐变透明度动画效果).scale(渐变尺寸伸缩动画效果).translate(画面转换位置移动动画效果).rotate(画面转移旋转动画效 ...

  3. 认识CSS样式

    CSS全称为“层叠样式表 (Cascading Style Sheets)”,它主要是用于定义HTML内容在浏览器内的显示样式,如文字大小.颜色.字体加粗等. 如下列代码: p{ font-size: ...

  4. Java学习----设计正真的应用程序

    import java.util.Scanner; // 输入10位学生的成绩,并且判断他们的成绩是哪个等级,其中90-100是A级,80-89是B级,70-79是C级,60-69是D级,60分以下E ...

  5. jquery 的attr()方法解析

    我想用jquery的attr()方法修改一个li小圆点的背景颜色和外边框的时候:刚开始 $("#shanghai-btn").attr({background:"#999 ...

  6. Spring MVC PageNotFound.noHandlerFound No mapping found for HTTP request with URI

    首先骂人,干他娘的,弄了两个小时原来的包倒错了!!唉TMD. 注意用IDEA倒包的时候一定要注意ModelAndView是 原因是import出错了!!应该是import org.springfram ...

  7. ActionResult派生类

    类名 抽象类 父类 功能 ContentResult 根据内容的类型和编码,数据内容. EmptyResult 空方法. FileResult abstract 写入文件内容,具体的写入方式在派生类中 ...

  8. jquery 当前页导航高亮显示

    <script type="text/javascript"> $(document).ready(function(){ var myNav = $("#n ...

  9. Linux socket编程 DNS查询IP地址

    本来是一次计算机网络的实验,但是还没有完全写好,DNS的响应请求报文的冗余信息太多了,不只有IP地址.所以这次的实验主要就是解析DNS报文.同时也需要正确的填充请求报文.如果代码有什么bug,欢迎指正 ...

  10. A题

    A - A Time Limit:1000MS     Memory Limit:131072KB     64bit IO Format:%I64d & %I64u   Descriptio ...